快速入門:使用 Bing 影像搜尋 REST API 和 C# 來搜尋影像Quickstart: Search for images using the Bing Image Search REST API and C#

使用本快速入門,開始將搜尋要求傳送至 Bing 影像搜尋 API。Use this quickstart to start sending search requests to the Bing Image Search API. 這個 C# 應用程式會將搜尋查詢傳送至 API,並顯示結果中第一個影像的 URL。This C# application sends a search query to the API, and displays the URL of the first image in the results. 雖然此應用程式是以 C# 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in C#, the API is a RESTful web service compatible with most programming languages.

此範例的原始程式碼可從 GitHub 取得,其中含有其他錯誤處理和註釋。The source code for this sample is available on GitHub with additional error handling and annotations.

必要條件Prerequisites

您必須有具備 Bing 搜尋 API 存取權的認知服務 API 帳戶You must have a Cognitive Services API account with access to the Bing Search APIs. 如果您沒有 Azure 訂用帳戶,可以建立免費帳戶If you don't have an Azure subscription, you can create an account for free. 繼續之前,您需要有啟動免費試用版後所提供的存取金鑰,或是從 Azure 儀表板中取得的付費訂用帳戶金鑰。Before continuing, You will need the access key provided after activating your free trial, or a paid subscription key from your Azure dashboard.

建立專案並將其初始化Create and initialize a project

  1. 在 Visual Studio 中建立一個名為 BingSearchApisQuickStart 的新主控台解決方案。create a new console solution named BingSearchApisQuickStart in Visual Studio. 然後將下列命名空間新增至主要程式碼檔案。Then add the following namespaces into the main code file.

    using System;
    using System.Net;
    using System.IO;
    using System.Collections.Generic;
    using Newtonsoft.Json.Linq;
    
  2. 建立適用於 API 端點、您訂用帳戶金鑰及搜尋字詞的變數。Create variables for the API endpoint, your subscription key, and search term.

    //...
    namespace BingSearchApisQuickstart
    {
        class Program
        {
        // Replace the this string with your valid access key.
        const string subscriptionKey = "enter your key here";
        const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/images/search";
        const string searchTerm = "tropical ocean";
    //...
    

建立結構來製作 Bing 影像搜尋回應的格式Create a struct to format the Bing Image Search response

定義 SearchResult 結構以包含影像搜尋結果及 JSON 標頭資訊。Define a SearchResult struct to contain the image search results, and JSON header information.

    namespace BingSearchApisQuickstart
    {
        class Program
        {
        //...
            struct SearchResult
            {
                public String jsonResult;
                public Dictionary<String, String> relevantHeaders;
            }
//...

建立方法來傳送搜尋要求Create a method to send search requests

建立一個名為 BingImageSearch 的方法來執行對 API 的呼叫,並將傳回類型設定為稍早建立的 SearchResult 結構。Create a method named BingImageSearch to perform the call to the API, and set the return type to the SearchResult struct created earlier.

//...
namespace BingSearchApisQuickstart
{
    //...
    class Program
    {
        //...
        static SearchResult BingImageSearch(string searchTerm)
        {
        }
//...

建立及處理影像搜尋要求Create and handle an image search request

BingImageSearch 方法中,執行下列步驟。In the BingImageSearch method, perform the following steps.

  1. 建構搜尋要求的 URI。Construct the URI for the search request. 搜尋字詞 SearchTerm 必須先格式化,才能附加到字串。The search term SearchTerm must be formatted before being appended to the string.

    static SearchResult BingImageSearch(string SearchTerm){
    
        var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(SearchTerm);
    //...
    
  2. 傳送 Web 要求並取得 JSON 字串形式的回應。Send the web request and get the response as a JSON string.

    WebRequest request = WebRequest.Create(uriQuery);
    request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey;
    HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
    string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
    
  3. 建立搜尋結果物件並擷取 Bing HTTP 標頭。Create the search result object, and extract the Bing HTTP headers. 然後傳回 searchResultThen return searchResult.

    // Create the result object for return
    var searchResult = new SearchResult()
    {
        jsonResult = json,
        relevantHeaders = new Dictionary<String, String>()
    };
    
    // Extract Bing HTTP headers
    foreach (String header in response.Headers)
    {
        if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
            searchResult.relevantHeaders[header] = response.Headers[header];
    }
    return searchResult;
    

處理及檢視回應Process and view the response

  1. 在主要方法中,呼叫 BingImageSearch() 並儲存傳回的回應。In the main method, call BingImageSearch() and store the returned response. 然後將 JSON 還原序列化成物件。Then deserialize the JSON into an object.

    SearchResult result = BingImageSearch(searchTerm);
    //deserialize the JSON response from the Bing Image Search API
    dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(result.jsonResult);
    
  2. jsonObj 取得第一個傳回的影像,並列印出影像的標題和 URL。Get the first returned image from jsonObj, and print out the title and a URL to the image.

    var firstJsonObj = jsonObj["value"][0];
    Console.WriteLine("Title for the first image result: " + firstJsonObj["name"]+"\n");
    //After running the application, copy the output URL into a browser to see the image.
    Console.WriteLine("URL for the first image result: " + firstJsonObj["webSearchUrl"]+"\n");
    

範例 JSON 回應Example JSON response

來自「Bing 影像搜尋 API」的回應會以 JSON 形式傳回。Responses from the Bing Image Search API are returned as JSON. 本範例回應已截斷而只顯示單一結果。This sample response has been truncated to show a single result.

{
"_type":"Images",
"instrumentation":{
    "_type":"ResponseInstrumentation"
},
"readLink":"images\/search?q=tropical ocean",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=tropical ocean&FORM=OIIARP",
"totalEstimatedMatches":842,
"nextOffset":47,
"value":[
    {
        "webSearchUrl":"https:\/\/www.bing.com\/images\/search?view=detailv2&FORM=OIIRPO&q=tropical+ocean&id=8607ACDACB243BDEA7E1EF78127DA931E680E3A5&simid=608027248313960152",
        "name":"My Life in the Ocean | The greatest WordPress.com site in ...",
        "thumbnailUrl":"https:\/\/tse3.mm.bing.net\/th?id=OIP.fmwSKKmKpmZtJiBDps1kLAHaEo&pid=Api",
        "datePublished":"2017-11-03T08:51:00.0000000Z",
        "contentUrl":"https:\/\/mylifeintheocean.files.wordpress.com\/2012\/11\/tropical-ocean-wallpaper-1920x12003.jpg",
        "hostPageUrl":"https:\/\/mylifeintheocean.wordpress.com\/",
        "contentSize":"897388 B",
        "encodingFormat":"jpeg",
        "hostPageDisplayUrl":"https:\/\/mylifeintheocean.wordpress.com",
        "width":1920,
        "height":1200,
        "thumbnail":{
        "width":474,
        "height":296
        },
        "imageInsightsToken":"ccid_fmwSKKmK*mid_8607ACDACB243BDEA7E1EF78127DA931E680E3A5*simid_608027248313960152*thid_OIP.fmwSKKmKpmZtJiBDps1kLAHaEo",
        "insightsMetadata":{
        "recipeSourcesCount":0,
        "bestRepresentativeQuery":{
            "text":"Tropical Beaches Desktop Wallpaper",
            "displayText":"Tropical Beaches Desktop Wallpaper",
            "webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=Tropical+Beaches+Desktop+Wallpaper&id=8607ACDACB243BDEA7E1EF78127DA931E680E3A5&FORM=IDBQDM"
        },
        "pagesIncludingCount":115,
        "availableSizesCount":44
        },
        "imageId":"8607ACDACB243BDEA7E1EF78127DA931E680E3A5",
        "accentColor":"0050B2"
    }]
}

後續步驟Next steps

另請參閱See also