次の方法で共有


クイック スタート: Bing Image Search REST API と C を使用して画像を検索する#

警告

2020 年 10 月 30 日、Bing Search API は Azure AI サービスから Bing Search Services に移行されました。 このドキュメントは参考用に提供されています。 更新されたドキュメントについては、Bing search API のドキュメントを参照してください。 Bing検索用の新しい Azure リソースを作成する手順については、「Azure Marketplace を使用して Bing Search リソースを作成するを参照してください。

このクイック スタートでは、Bing Image Search API に検索要求を送信する方法について説明します。 この C# アプリケーションは、API に検索クエリを送信し、結果の最初の画像の URL を表示します。 このアプリケーションは C# で記述されていますが、API はほとんどのプログラミング言語と互換性のある RESTful Web サービスです。

前提条件

プロジェクトを作成して初期化する

  1. Visual Studio で BingSearchApisQuickStart という名前の新しいコンソール ソリューションを作成します。 次に、次の名前空間をメイン コード ファイルに追加します。

    using System;
    using System.Net;
    using System.IO;
    using System.Collections.Generic;
    using Newtonsoft.Json.Linq;
    
  2. API エンドポイント、サブスクリプション キー、検索用語の変数を作成します。 uriBaseの場合は、次のコードでグローバル エンドポイントを使用するか、リソースの Azure portal に表示される カスタム サブドメイン エンドポイントを使用できます。

    //...
    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 Image Search 応答を書式設定する構造体を作成する

画像の検索結果と JSON ヘッダー情報を格納する SearchResult 構造体を定義します。

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

検索要求を送信するメソッドを作成する

api の呼び出しを実行する BingImageSearch という名前のメソッドを作成し、戻り値の型を前に作成した SearchResult 構造体に設定します。

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

イメージ検索要求を作成して処理する

BingImageSearch メソッドで、次の手順を実行します。

  1. 検索要求の URI を構築します。 文字列に追加する前に、 SearchTerm 検索用語の書式を設定します。

    static SearchResult BingImageSearch(string SearchTerm){
    
        var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(SearchTerm);
    //...
    
  2. Web 要求を送信し、JSON 文字列として応答を取得します。

    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 ヘッダーを抽出します。 次に、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;
    

応答を処理して表示する

  1. main メソッドで、BingImageSearch() を呼び出し、返された応答を格納します。 次に、JSON をオブジェクトに逆シリアル化します。

    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 を出力します。

    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 応答の例

Bing Image Search API からの応答は JSON として返されます。 このサンプル応答は、1 つの結果を表示するために切り捨てられました。

{
"_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"
    }]
}

次のステップ

こちらもご覧ください