什么是谷歌图片搜索API?
谷歌官方是这么说得:The Google Image Search API provides a JavaScript interface to embed? Google Image Search ? results in your website or application.(谷歌提供的基于javascript的图片搜索api可以嵌入到你的网站和应用中)
下面就进行我们谷歌图片api开发之旅,首先我们知道谷歌有很多api,比如Google Map Api、Blog Serach Api等等等等。。。
我们怎么去学习呢?其实这些我们都不用去学习,等我们用着的直接去官方找资料即可。下面就以图片搜索API为例,在对其一无所知的情况下,构建自己的一个应用。
第一:我们直接在google里面搜索 google api 会出来很多结果一般前几个都是google map api;点击进入到http://code.google.com/intl/zh-CN/
左侧找到ajax api 点击进入 然后左侧可以看见 image search ,这就是google api了,点击进入。我们怎么去做呢,看右边有个How do? i start?
第一项是需要注册一个账号,申请一个key,不用怎么说
第二项进去之后我们点击 JSON Developer's Guide 进去后 直接找 code example 找关于java的
URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" + "v=1.0&q=barack%20obama&key=INSERT-YOUR-KEY&userip=INSERT-USER-IP"); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", /* Enter the URL of your site here */); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while((line = reader.readLine()) != null) { builder.append(line); } JSONObject json = new JSONObject(builder.toString()); // now have some fun with the results...?其实现在这个简单的应用就可以了
下面这个应用是我结合jquery做得一个基于google image api的图片浏览应用 代码很简单,开放出来供大家参考
还是贴代码吧
1.index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>图片搜索引擎(仅供学习用QQ:三二八二四七六七六)</title> <link rel="stylesheet" type="text/css" href="css/style.css" /> <script type="text/javascript" src="js/jquery-1.4.4.js"></script> <script type="text/javascript" src="js/getimg.js"></script> </head> <body> <div align="center"> <input type="text" id="categoryName" width=500> <input type="radio" name="picSource" value="google" checked hidden="true"></input> <input type="button" value="搜索" id="button1"> <input type="button" value="清空" id="clear"> </div> <div id="showPhoto"> <!-- 显示大图 --> <img src="images/close.jpg" id="close" /> <div id="showPic"> <img> </div> <div id="bgblack"></div> <!-- 用来显示透明的黑色背景 --> <div id="navigator"> </div> </div> </body> </html>
?2.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>ImageServlet</servlet-name> <servlet-class>servlet.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ImageServlet</servlet-name> <url-pattern>/ImageServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
?3.getimg.js
var iPicNum = 64; var index; var array; $(function() { $("#showPhoto").hide(); $("#bgblack").css("opacity", 0.9); // 显示大图的方块背景设置为透明 $("#clear").click(function() { window.location.reload(); }); $("#close").click(function() { // 点击按钮close,则关闭大图面板(采用动画) $("#showPhoto").add("#showPic").fadeOut(400); }); $("#button1").click(function() { $(document.body) .append("<div id='load' align='center'><img src='images/loading.gif'</div>"); $.get("ImageServlet", { categoryName : encodeURI($("#categoryName").val()), picSource : $("input[name=picSource]:checked").val() }, function(returnedData, status) { var html = ""; for (var i = 0; i < returnedData.length; i++) { html += "<div><a href='#'><img id='img" + i + "' src='" + returnedData[i] + "' width='150' height='150'></a></div>"; } $(document.body).append(html); $('#load').hide(); $("div:has(a)").addClass("thumb"); $("div a:has(img)").click(function() { // 如果点击缩略图,则显示大图 $("#showPhoto").css({ // 大图的位置根据窗口来判断 "left" : ($(window).width() / 2 - 300 > 20 ? $(window).width() / 2 - 300 : 20), "top" : ($(window).height() / 2 - 270 > 30 ? $(window).height() / 2 - 270 : 30) }).add("#showPic").fadeIn(400); // 根据缩略图的地址,获取相应的大图地址 var mySrc = $(this).find("img").attr("src"); var img = $("#showPic").find("img"); var showimg = new Image(); showimg.src = mySrc; var imgWidth = showimg.width; var imgHeight = showimg.height; var boxWidth = 400; var boxHeight = 400; if ((boxWidth / boxHeight) >= (imgWidth / imgHeight)) { // 重新设置img的width和height img.width((boxHeight * imgWidth) / imgHeight); img.height(boxHeight); // 让图片居中显示 var margin = (boxWidth - img.width()) / 2; // img.css("margin-left",margin); } else { // 重新设置img的width和height img.width(boxWidth); img.height((boxWidth * imgHeight) / imgWidth); // 让图片居中显示 var margin = (boxHeight - img.height()) / 2; // img.css("margin-top",margin); } img.attr("src", mySrc); if ($(this).parent().hasClass("ls")) // 根据图片属性(水平或者竖直),调整大图的位置 $("#showPic").find("img").css("marginTop", "70px"); else if ($(this).parent().hasClass("pt")) $("#showPic").find("img").css("marginTop", "0px"); }); for (var i = 0; i < iPicNum; i++) { var myimg = new Image(); myimg.src = $("div a img").get(i).src; // 根据图片的比例(水平或者竖直),添加不同的样式 if (myimg.width > myimg.height) $("div:has(a):eq(" + i + ")").addClass("ls"); else $("div:has(a):eq(" + i + ")").addClass("pt"); } }); }); });
?4.ImageServlet.java
package servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.JSONArray; import org.json.JSONObject; import com.google.gson.Gson; public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String urlString = "http://ajax.googleapis.com/ajax/services/search/images?key=ABQIAAAAHMkDJuY1vzGaqUjliVAN-RSo6_Y-lPd_7a5rWdJRsISKKsAXgBQyI4z9PBvV4NjKXO02MH68cek4yA&rsz=large&v=1.0&"; String categoryName = URLDecoder.decode(URLDecoder.decode( request.getParameter("categoryName"), "utf-8").trim(), "utf-8"); String picSource = request.getParameter("picSource"); List<String> returnedList = new ArrayList<String>(); HttpSession session = request.getSession(); session.setAttribute("categoryName", categoryName); session.setAttribute("picSource", picSource); session.setAttribute("images", returnedList); // 存储每次从Google所获取的json数据 List<String> list = new ArrayList<String>(); for (int i = 0; i < 8; i++) { String queryString = new StringBuffer(urlString).append("q=") .append(categoryName).append("&start=").append(8 * i) .toString(); System.out.println(queryString); list.add(getStringContentFromURL(queryString)); } for (String result : list) { JSONObject jsonContent = new JSONObject(result); JSONObject responseData = jsonContent .getJSONObject("responseData"); JSONArray results = responseData.getJSONArray("results"); for (int i = 0; i < results.length(); i++) { JSONObject jsonObject = results.getJSONObject(i); String url = jsonObject.getString("url"); returnedList.add(url); } } Gson gson = new Gson(); String jsonResult = gson.toJson(returnedList); response.setContentType("application/json; charset=utf-8"); response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-cache"); PrintWriter out = response.getWriter(); out.print(jsonResult); out.flush(); } catch (Exception ex) { ex.printStackTrace(); } } public String getStringContentFromURL(String queryString) throws Exception { URL url = new URL(queryString); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuffer buffer = new StringBuffer(); String line = null; while (null != (line = br.readLine())) { buffer.append(line); } br.close(); isr.close(); is.close(); return buffer.toString(); } }
?再截张图看看
不足之处还有很多,欢迎指正与批评。批评QQ:三2八二四7六七六