クイック スタート:Bing Image Search クライアント ライブラリを使用する

警告

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

このクイックスタートでは、Bing Image Search クライアント ライブラリを使用して最初の画像検索を行います。

このクライアント検索ライブラリは、REST API のラッパーであり、同じ機能を含んでいます。

ここでは、画像検索クエリを送信し、JSON 応答を解析して、返された最初の画像の URL を表示する C# アプリケーションを作成します。

前提条件

Azure AI サービスの価格 - Bing Search API に関するページもご覧ください。

コンソール プロジェクトを作成する

まず、新しい C# コンソール アプリケーションを作成します。

  1. Visual Studio で、BingImageSearch という新しいコンソール ソリューションを作成します。

  2. Cognitive Image Search NuGet パッケージを追加します。

    1. ソリューション エクスプローラーでプロジェクトを右クリックします。
    2. [NuGet パッケージの管理] を選択します。
    3. Microsoft.Azure.CognitiveServices.Search.ImageSearch を検索して選択し、このパッケージをインストールします。

アプリケーションを初期化する

  1. Program.cs 内のすべての using ステートメントを次のコードに置き換えます。

    using System;
    using System.Linq;
    using Microsoft.Azure.CognitiveServices.Search.ImageSearch;
    using Microsoft.Azure.CognitiveServices.Search.ImageSearch.Models;
    
  2. プロジェクトの Main メソッドでは、有効なサブスクリプション キー、Bing で返す必要のある画像の結果、および検索語句の変数を作成します。 その後、キーを使用して画像検索クライアントをインスタンス化します。

    static async Task Main(string[] args)
    {
        //IMPORTANT: replace this variable with your Cognitive Services subscription key
        string subscriptionKey = "ENTER YOUR KEY HERE";
        //stores the image results returned by Bing
        Images imageResults = null;
        // the image search term to be used in the query
        string searchTerm = "canadian rockies";
    
        //initialize the client
        //NOTE: If you're using version 1.2.0 or below for the Bing Image Search client library, 
        // use ImageSearchAPI() instead of ImageSearchClient() to initialize your search client.
    
        var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey));
    }
    

クライアントを使用して検索クエリを送信する

引き続き Main メソッドで、クライアントを使用してクエリ テキストを検索します。

// make the search request to the Bing Image API, and get the results"
imageResults = await client.Images.SearchAsync(query: searchTerm).Result; //search query

最初の画像の結果を解析して表示する

応答で返された画像の結果を解析します。

応答に検索結果が含まれている場合は、最初の結果を格納して、その詳細の一部を出力します。

if (imageResults != null)
{
    //display the details for the first image result.
    var firstImageResult = imageResults.Value.First();
    Console.WriteLine($"\nTotal number of returned images: {imageResults.Value.Count}\n");
    Console.WriteLine($"Copy the following URLs to view these images on your browser.\n");
    Console.WriteLine($"URL to the first image:\n\n {firstImageResult.ContentUrl}\n");
    Console.WriteLine($"Thumbnail URL for the first image:\n\n {firstImageResult.ThumbnailUrl}");
    Console.WriteLine("Press any key to exit ...");
    Console.ReadKey();
}

次のステップ

関連項目

このクイックスタートでは、Bing Image Search クライアント ライブラリを使用して最初の画像検索を行います。このクライアント ライブラリは、API のラッパーであり、同じ機能を含んでいます。 このシンプルな Java アプリケーションは、画像検索クエリを送信し、JSON 応答を解析して、返された最初のイメージの URL を表示します。

前提条件

最新バージョンの Java Development Kit (JDK)

Maven、Gradle、または別の依存関係管理システムを使用して Bing Image Search クライアント ライブラリの依存関係をインストールします。 Maven POM ファイルには、次の宣言が必要です。

 <dependencies>
    <dependency>
      <groupId>com.microsoft.azure.cognitiveservices</groupId>
      <artifactId>azure-cognitiveservices-imagesearch</artifactId>
      <version>1.0.1</version>
    </dependency>
 </dependencies>

アプリケーションを作成して初期化する

  1. お気に入りの IDE またはエディターで新しい Java プロジェクトを作成し、次のインポートをクラスの実装に追加します。

    import com.microsoft.azure.cognitiveservices.search.imagesearch.BingImageSearchAPI;
    import com.microsoft.azure.cognitiveservices.search.imagesearch.BingImageSearchManager;
    import com.microsoft.azure.cognitiveservices.search.imagesearch.models.ImageObject;
    import com.microsoft.azure.cognitiveservices.search.imagesearch.models.ImagesModel;
    
  2. メイン メソッドで、サブスクリプション キーと検索用語の変数を作成します。 次に、Bing Image Search クライアントをインスタンス化します。

    final String subscriptionKey = "COPY_YOUR_KEY_HERE";
    String searchTerm = "canadian rockies";
    //Image search client
    BingImageSearchAPI client = BingImageSearchManager.authenticate(subscriptionKey);
    

API に検索要求を送信します。

  1. bingImages().search() を使用して、検索クエリを含む HTTP 要求を送信します。 応答を ImagesModel として保存します。

    ImagesModel imageResults = client.bingImages().search()
                .withQuery(searchTerm)
                .withMarket("en-us")
                .execute();
    

結果を解析して表示する

応答で返された画像の結果を解析します。 応答に検索結果が含まれている場合は、最初の結果を格納して、返された URL の合計数と共にサムネイルの URL などの詳細を出力します。

if (imageResults != null && imageResults.value().size() > 0) {
    // Image results
    ImageObject firstImageResult = imageResults.value().get(0);

    System.out.println(String.format("Total number of images found: %d", imageResults.value().size()));
    System.out.println(String.format("First image thumbnail url: %s", firstImageResult.thumbnailUrl()));
    System.out.println(String.format("First image content url: %s", firstImageResult.contentUrl()));
}
else {
        System.out.println("Couldn't find image results!");
     }

次のステップ

関連項目

このクイックスタートでは、Bing Image Search クライアント ライブラリを使用して最初の画像検索を行います。このクライアント ライブラリは、API のラッパーであり、同じ機能を含んでいます。 このシンプルな JavaScript アプリケーションは、イメージ検索クエリを送信し、JSON 応答を解析して、返された最初のイメージの URL を表示します。

前提条件

  • 最新バージョンの Node.js
  • Bing Image Search SDK for JavaScript
    • インストールするには、npm install @azure/cognitiveservices-imagesearch を実行します
  • クライアントを認証するための CognitiveServicesCredentials クラス (@azure/ms-rest-azure-js パッケージに含まれています)。
    • インストールするには、npm install @azure/ms-rest-azure-js を実行します

アプリケーションを作成して初期化する

  1. 好みの IDE またはエディターで新しい JavaScript ファイルを作成し、厳格度、https、およびその他の要件を設定します。

    'use strict';
    const ImageSearchAPIClient = require('@azure/cognitiveservices-imagesearch');
    const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
    
  2. プロジェクトの main メソッドでは、有効なサブスクリプション キー、Bing で返す必要のある画像の結果、および検索語句の変数を作成します。 その後、キーを使用して画像検索クライアントをインスタンス化します。

    //replace this value with your valid subscription key.
    let serviceKey = "ENTER YOUR KEY HERE";
    
    //the search term for the request
    let searchTerm = "canadian rockies";
    
    //instantiate the image search client
    let credentials = new CognitiveServicesCredentials(serviceKey);
    let imageSearchApiClient = new ImageSearchAPIClient(credentials);
    
    

非同期ヘルパー関数を作成する

  1. クライアントを非同期に呼び出す関数を作成し、Bing Image Search サービスから応答を返します。

    // a helper function to perform an async call to the Bing Image Search API
    const sendQuery = async () => {
        return await imageSearchApiClient.imagesOperations.search(searchTerm);
    };
    

クエリを送信して応答を処理する

  1. ヘルパー関数を呼び出して promise を処理し、応答で返されたイメージの結果を解析します。

    応答に検索結果が含まれている場合は、最初の結果を格納して、返された URL の合計数と共にサムネイルの URL などの詳細を出力します。

    sendQuery().then(imageResults => {
        if (imageResults == null) {
        console.log("No image results were found.");
        }
        else {
            console.log(`Total number of images returned: ${imageResults.value.length}`);
            let firstImageResult = imageResults.value[0];
            //display the details for the first image result. After running the application,
            //you can copy the resulting URLs from the console into your browser to view the image.
            console.log(`Total number of images found: ${imageResults.value.length}`);
            console.log(`Copy these URLs to view the first image returned:`);
            console.log(`First image thumbnail url: ${firstImageResult.thumbnailUrl}`);
            console.log(`First image content url: ${firstImageResult.contentUrl}`);
        }
      })
      .catch(err => console.error(err))
    

次のステップ

関連項目

このクイックスタートでは、Bing Image Search クライアント ライブラリを使用して最初の画像検索を行います。このクライアント ライブラリは、API のラッパーであり、同じ機能を含んでいます。 このシンプルな Python アプリケーションは、画像検索クエリを送信し、JSON 応答を解析して、返された最初の画像の URL を表示します。

前提条件

アプリケーションを作成して初期化する

  1. お気に入りの IDE またはエディターで新しい Python スクリプトを作成し、次のインポートを行います。

    from azure.cognitiveservices.search.imagesearch import ImageSearchClient
    from msrest.authentication import CognitiveServicesCredentials
    
  2. サブスクリプション キーと検索用語の変数を作成します。

    subscription_key = "Enter your key here"
    subscription_endpoint = "Enter your endpoint here"
    search_term = "canadian rockies"
    

画像検索クライアントを作成する

  1. CognitiveServicesCredentials のインスタンスを作成し、それを使用してクライアントをインスタンス化します。

    client = ImageSearchClient(endpoint=subscription_endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  2. Bing Image Search API に検索クエリを送信します。

    image_results = client.images.search(query=search_term)
    

結果の処理と表示

応答で返された画像の結果を解析します。

応答に検索結果が含まれている場合は、最初の結果を格納して、返された URL の合計数と共にサムネイルの URL などの詳細を出力します。

if image_results.value:
    first_image_result = image_results.value[0]
    print("Total number of images returned: {}".format(len(image_results.value)))
    print("First image thumbnail url: {}".format(
        first_image_result.thumbnail_url))
    print("First image content url: {}".format(first_image_result.content_url))
else:
    print("No image results returned!")

次のステップ

関連項目