在智慧型裝置專案、Windows Form 應用程式與 Widget 使用 Bing API 達成 Bing 圖片搜尋
1. 簡介
Bing 是微軟開發的搜尋引擎,使用者可透過 Bing API 開發程式,本文使用 Bing API 做圖片搜尋,實做於 Smart Device Application、Windows Form Application、 Widget。
想要使用 Bing API,需申請 AppID,
於網址 http://www.bing.com/developers/default.aspx,使用 Live Passport 登入,並輸入相關資訊,註冊後得到一組 AppID
2. 方法
以下針對 Smart Device Application、Windows Form Application、 Widget 開發 Bing 圖片搜尋做介紹
2.1 智慧型裝置專案
(1) 加入 Web 參考
在 [URL] 中輸入 http://api.search.live.net/search.wsdl?AppID=申請的AppID,修改 [Web 參考名稱],點選 [加入參考]
在程式中 using 專案名稱.參考名稱
using SmartDeviceBing.net.live.search.api;
(2) 程式碼
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SmartDeviceBing.net.live.search.api;
namespace SmartDeviceBing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
// LiveSearchService implements IDisposable.
using (LiveSearchService service = new LiveSearchService())
{
try
{
SearchRequest request = BuildRequestWeb();
// Send the request; display the response.
SearchResponse response = service.Search(request);
DisplayResponseWeb(response);
}
catch (System.Net.WebException ex)
{
MessageBox.Show(ex.Message);
}
}
}
private SearchRequest BuildRequestWeb()
{
SearchRequest request = new SearchRequest();
// Common request fields (required)
request.AppId = "B692A148D1624C4E3C1248C8E5DDC209E524D2C4";
request.Query = this.txtQuery.Text;
request.Sources = new SourceType[] { SourceType.Image };
// Common request fields (optional)
request.Version = "2.0";
request.Market = "en-us";
request.Adult = AdultOption.Moderate;
request.AdultSpecified = true;
request.Options = new SearchOption[]
{
SearchOption.EnableHighlighting
};
// Web-specific request fields (optional)
request.Web = new WebRequest();
request.Web.Count = 10;
request.Web.CountSpecified = true;
request.Web.Offset = 0;
request.Web.OffsetSpecified = true;
request.Web.Options = new WebSearchOption[]
{
WebSearchOption.DisableHostCollapsing,
WebSearchOption.DisableQueryAlterations
};
return request;
}
private void DisplayResponseWeb(SearchResponse response)
{
this.lstView.Items.Clear();
// Display the results header.
this.labBing.Text = string.Format("Displaying {0} to {1} of {2} results",
response.Image.Offset + 1,
response.Image.Offset + response.Image.Results.Count(),
response.Image.Total);
// Display the Image results.
foreach (ImageResult result in response.Image.Results)
{
ListViewItem lvItem = new ListViewItem(result.Title);
lvItem.SubItems.Add(result.MediaUrl);
lvItem.SubItems.Add(result.Width + "x" + result.Height);
this.lstView.Items.Add(lvItem);
}
}
private void lstView_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < lstView.Items.Count; i++ )
{
if (lstView.Items[i].Selected)
{
// 讀取網路圖片到 PictureBox
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(lstView.Items[i].SubItems[1].Text);
System.Net.HttpWebResponse rsp = (System.Net.HttpWebResponse)req.GetResponse();
if (rsp.StatusCode == System.Net.HttpStatusCode.OK)
{
this.PicBoxPhoto.Image = new Bitmap(rsp.GetResponseStream());
}
rsp.Close();
}
}
}
}
}
(3) 執行結果
2.2 Windows Form 應用程式
(1) 加入 服務參考
在 [位址] 中輸入 http://api.search.live.net/search.wsdl?AppID=申請的AppID,修改 [命名空間],點選 [確定]
在程式中 using 專案名稱.參考名稱
using WindowsFormsBing.ServiceReference1;
(2) 程式碼
以下程式碼 2.1 智慧型裝置的程式碼類似,不同點標示於程式碼中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsFormsBing.ServiceReference1;
namespace WindowsFormsBing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
// LiveSearchPortTypeClient implements IDisposable.
using (LiveSearchPortTypeClient client = new LiveSearchPortTypeClient()) // WindowsForms應用程式與智慧型裝置的差異
{
try
{
SearchRequest request = BuildRequestWeb();
// Send the request; display the response.
SearchResponse response = client.Search(request);
DisplayResponseWeb(response);
}
catch (System.Net.WebException ex)
{
MessageBox.Show(ex.Message);
}
}
}
private SearchRequest BuildRequestWeb()
{
SearchRequest request = new SearchRequest();
// Common request fields (required)
request.AppId = "B692A148D1624C4E3C1248C8E5DDC209E524D2C4";
request.Query = this.txtQuery.Text;
request.Sources = new SourceType[] { SourceType.Image };
// Common request fields (optional)
request.Version = "2.0";
request.Market = "en-us";
request.Adult = AdultOption.Moderate;
request.AdultSpecified = true;
request.Options = new SearchOption[]
{
SearchOption.EnableHighlighting
};
// Web-specific request fields (optional)
request.Web = new WebRequest();
request.Web.Count = 10;
request.Web.CountSpecified = true;
request.Web.Offset = 0;
request.Web.OffsetSpecified = true;
request.Web.Options = new WebSearchOption[]
{
WebSearchOption.DisableHostCollapsing,
WebSearchOption.DisableQueryAlterations
};
return request;
}
private void DisplayResponseWeb(SearchResponse response)
{
this.lstView.Items.Clear();
// Display the results header.
this.labBing.Text = string.Format("Displaying {0} to {1} of {2} results",
response.Image.Offset + 1,
response.Image.Offset + response.Image.Results.Count(),
response.Image.Total);
// Display the Image results.
foreach (ImageResult result in response.Image.Results)
{
ListViewItem lvItem = new ListViewItem(result.Title);
lvItem.SubItems.Add(result.MediaUrl);
lvItem.SubItems.Add(result.Width + "x" + result.Height);
this.lstView.Items.Add(lvItem);
}
}
private void lstView_SelectedIndexChanged(object sender, EventArgs e)
{
// 簡化讀取網路圖片的寫法
if (lstView.SelectedItems.Count > 0)
{
this.PicBoxPhoto.Image = null;
this.PicBoxPhoto.ImageLocation = lstView.SelectedItems[0].SubItems[1].Text;
this.PicBoxPhoto.Refresh();
}
//for (int i = 0; i < lstView.Items.Count; i++)
//{
// if (lstView.Items[i].Selected)
// {
// // 讀取網路圖片到 PictureBox
// System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(lstView.Items[i].SubItems[1].Text);
// System.Net.HttpWebResponse rsp = (System.Net.HttpWebResponse)req.GetResponse();
// if (rsp.StatusCode == System.Net.HttpStatusCode.OK)
// {
// this.PicBoxPhoto.Image = new Bitmap(rsp.GetResponseStream());
// }
// rsp.Close();
// }
//}
}
}
}
(3) 執行結果
2.3 Widget
Widget 是 Windows Mobile 6.5 強打的功能,而 Bing API 有許多功能可以做結合運用,尤其 Bing API 提供了許多範例程式,可以讓開發者很容易上手。
*註 : Widget 開發部分可參考之前的文章 [Windows Mobile]修練筆記(3) - 撰寫 Widget 工具,讀取 MSDN Magazine RSS 文章標題與連結
而本文中的 Widget 三個主要檔案,HTML file、config.xml file、ico file 當中的 HTML file 則是使用範例程式中的 ImageSample.html 做修改。
功能主要為使用者輸入 key word 後,點選 Search,透由 Bing API 送回JSON格式的結果,並將資訊整理後顯示。
(1) HTML file
file name : widget.htm
註 : 以下程式碼貼上 blog 後,有 lost現象,有需要程式碼的人可直接到文章最後下載
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bing API Image Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
var AppId = "B692A148D1624C4E3C1248C8E5DDC209E524D2C4"; // Insert your AppId here.
function Search( varQuery ) {
var requestStr = "http://api.search.live.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=" + varQuery
+ "&Sources=Image"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Adult=Moderate"
// Image-specific request fields (optional)
+ "&Image.Count=10"
+ "&Image.Offset=0"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
var requestScript = document.createElement("script");
requestScript.type = "text/javascript";
requestScript.src = requestStr;
var head = document.getElementsByTagName("head");
head[0].appendChild(requestScript);
}
function SearchCompleted(response) {
var errors = response.SearchResponse.Errors;
if (errors != null) {
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else {
// There were no errors in the response. Display the Image results.
DisplayResults(response);
}
}
function DisplayResults(response) {
ClearOutput(); // Clear.
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Image.Results;
// Display the results header.
resultsHeader.innerHTML = "Image results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Image.Offset + 1)
+ " to "
+ (response.SearchResponse.Image.Offset + results.length)
+ " of "
+ response.SearchResponse.Image.Total
+ " results<br />";
// Display the Image results.
var resultsListItem = null;
for (var i = 0; i < results.length; ++i) {
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
resultsListItem.innerHTML = "<a href=\""
+ results[i].MediaUrl
+ "\"><img src=\""
+ results[i].Thumbnail.Url
+ "\"></a><br /><a href=\""
+ results[i].Url
+ "\">"
+ results[i].Title
+ "</a><br />Dimensions: "
+ results[i].Width
+ "x"
+ results[i].Height
+ "<br /><br />";
}
}
function DisplayErrors(errors) {
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i) {
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i]) {
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
function ClearOutput() {
output.innerHTML = "";
}
function ButtonSearch_onclick() {
Search(TextQuery.value);
}
</script>
</head>
<body>
<div>
<input id="TextQuery" type="text" />
<input id="ButtonSearch" type="button" value="Search" onclick="return ButtonSearch_onclick()" />
</div>
<div id="output"></div>
</body>
</html>
(2) config.xml file
file name : config.xml
<?xml version="1.0" encoding="utf-8" ?>
<widget xmlns="http://www.w3.org/ns/widgets" version="1.0">
<name>Bing Image Search</name>
<content src="widget.htm" type="text/html" />
<access network="true" />
<icon src="icon.jpg"/>
<description>This is widget by using Bing API</description>
</widget>
(3) 執行結果
3. 參考
Lolota [How to]Bing API開發初體驗
Puma [Mobile]Windows Mobile 6.5 Widget - Widget 結合 Bing API(JSON) 翻譯功能
4. 檔案下載