快速入門:使用 Bing 影像搜尋用戶端程式庫

警告

在 2020 年 10 月 30 日,Bing 搜尋 API 已從 Azure AI 服務移至 Bing 搜尋 服務。 本文件僅供參考之用。 如需更新的文件,請參閱 Bing 搜尋 API 文件。 如需針對 Bing 搜尋建立新 Azure 資源的指示,請參閱透過 Azure Marketplace 建立 Bing 搜尋資源

您可以透過此快速入門,完成初次使用此 SDK 進行的影像搜尋。

Bing 影像搜尋用戶端程式庫是 API 的包裝函式,而且功能相同,

您可以建立 C# 應用程式來傳送影像搜尋查詢、剖析 JSON 回應,以及顯示第一個傳回影像的 URL。

必要條件

另請參閱Azure AI 服務定價 - Bing 搜尋 API

建立主控台專案

首先建立新的 C# 主控台應用程式。

  1. 在 Visual Studio 中建立一個名為 BingImageSearch 的新主控台解決方案。

  2. 新增 認知影像搜尋 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 影像搜尋用戶端程式庫是 API 的包裝函式,而且功能相同,您可以透過此快速入門,完成初次使用此 SDK 進行的影像搜尋。 這個簡單的 Java 應用程式會傳送影像搜尋查詢、剖析 JSON 回應,以及顯示第一個傳回影像的 URL。

必要條件

最新版的 Java Development Kit (JDK)

使用 Maven、Gradle 或另一個相依性管理系統,來安裝 Bing 影像搜尋用戶端程式庫相依性。 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 影像搜尋用戶端具現化。

    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 影像搜尋用戶端程式庫是 API 的包裝函式,而且功能相同,您可以透過此快速入門,完成初次使用此 SDK 進行的影像搜尋。 這個簡單的 JavaScript 應用程式會傳送影像搜尋查詢、剖析 JSON 回應,以及顯示第一個回傳影像的 URL。

必要條件

  • 最新版的 Node.js
  • 適用於 JavaScript 的 Bing 影像搜尋 SDK
    • 若要安裝,請執行 npm install @azure/cognitiveservices-imagesearch
  • 來自 @azure/ms-rest-azure-js 套件中的 CognitiveServicesCredentials 類別,用來驗證用戶端。
    • 若要安裝,請執行 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. 在專案的主要方法中,針對有效訂用帳戶金鑰、要由 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 影像搜尋服務傳回回應。

    // 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 影像搜尋用戶端程式庫是 API 的包裝函式,而且功能相同,您可以透過此快速入門,完成初次使用此 SDK 進行的影像搜尋。 這個簡單的 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 影像搜尋 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!")

後續步驟

另請參閱