快速入门:使用必应图像搜索客户端库
警告
2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅必应搜索 API 文档。 关于为必应搜索创建新的 Azure 资源的说明,请参阅通过 Azure 市场创建必应搜索资源。
在本快速入门中,你将使用必应图像搜索客户端库进行第一次图像搜索。
客户端搜索库是 REST API 的包装器,并且包含相同的功能。
你将创建一个 C# 应用程序,发送图像搜索查询、分析 JSON 响应,并显示所返回的第一个图像的 URL。
先决条件
- 如果你正在使用 Windows,请使用任何版本的 Visual Studio 2017 或更高版本
- 如果你使用的是 macOS 或 Linux,请使用已安装 .NET Core 的 VS Code
- 免费的 Azure 订阅
另请参阅 Azure AI 服务定价 - 必应搜索 API。
创建控制台项目
首先,创建新的 C# 控制台应用程序。
在 Visual Studio 中创建一个名为 BingImageSearch 的新控制台解决方案。
-
- 在“解决方案资源管理器”中右键单击项目。
- 选择“管理 NuGet 包”。
- 搜索并选择“Microsoft.Azure.CognitiveServices.Search.ImageSearch”,然后安装该包。
初始化应用程序
用以下代码替换 Program.cs 中的所有
using
语句:using System; using System.Linq; using Microsoft.Azure.CognitiveServices.Search.ImageSearch; using Microsoft.Azure.CognitiveServices.Search.ImageSearch.Models;
在项目的
Main
方法中,创建你的有效订阅密钥的变量、必应要返回的图像结果和搜索词。 然后,使用密钥实例化图像搜索客户端。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();
}
后续步骤
另请参阅
在本快速入门中,你将使用必应图像搜索客户端库(它是 API 的包装器并包含相同的功能)进行你的第一次图像搜索。 这个简单的 Java 应用程序会发送图像搜索查询、分析 JSON 响应,并显示所返回的第一个图像的 URL。
先决条件
最新版的 Java 开发工具包 (JDK)
通过使用 Maven、Gradle 或其他依赖项管理系统安装必应图像搜索客户端库依赖项。 Maven POM 文件需要以下声明:
<dependencies>
<dependency>
<groupId>com.microsoft.azure.cognitiveservices</groupId>
<artifactId>azure-cognitiveservices-imagesearch</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
创建并初始化应用程序
在喜欢的 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;
在 main 方法中,为订阅密钥创建变量,并创建搜索词。 然后,对必应图像搜索客户端进行实例化。
final String subscriptionKey = "COPY_YOUR_KEY_HERE"; String searchTerm = "canadian rockies"; //Image search client BingImageSearchAPI client = BingImageSearchManager.authenticate(subscriptionKey);
向 API 发送搜索请求
使用
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!");
}
后续步骤
另请参阅
在本快速入门中,你将使用必应图像搜索客户端库(它是 API 的包装器并包含相同的功能)进行你的第一次图像搜索。 此简单的 JavaScript 应用程序发送图像搜索查询,分析 JSON 响应,并显示返回的第一个图像的 URL。
先决条件
- 最新版本的 Node.js。
- 适用于 JavaScript 的必应图像搜索 SDK
- 若要安装,请运行
npm install @azure/cognitiveservices-imagesearch
- 若要安装,请运行
@azure/ms-rest-azure-js
包中的CognitiveServicesCredentials
类,用于对客户端进行身份验证。- 若要安装,请运行
npm install @azure/ms-rest-azure-js
- 若要安装,请运行
创建并初始化应用程序
在你喜欢使用的 IDE 或编辑器中创建一个新的 JavaScript 文件,设置严格性、https 和其他要求。
'use strict'; const ImageSearchAPIClient = require('@azure/cognitiveservices-imagesearch'); const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
在项目的主方法中,创建你的有效订阅密钥的变量、必应要返回的图像结果和搜索词。 然后,使用密钥实例化图像搜索客户端。
//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);
创建异步帮助程序函数
创建一个以异步方式调用客户端的函数,并从必应图像搜索服务返回响应。
// a helper function to perform an async call to the Bing Image Search API const sendQuery = async () => { return await imageSearchApiClient.imagesOperations.search(searchTerm); };
发送查询并处理响应
调用帮助程序函数并处理其
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))
后续步骤
另请参阅
在本快速入门中,你将使用必应图像搜索客户端库(它是 API 的包装器并包含相同的功能)进行你的第一次图像搜索。 此简单的 Python 应用程序发送图像搜索查询,分析 JSON 响应,并显示返回的第一个图像的 URL。
先决条件
适用于 Python 的 Azure 图像搜索客户端库
- 使用
pip install azure-cognitiveservices-search-imagesearch
进行安装
- 使用
创建并初始化应用程序
在最喜爱的 IDE 或编辑器中创建新的 Python 脚本,然后将发生以下导入:
from azure.cognitiveservices.search.imagesearch import ImageSearchClient from msrest.authentication import CognitiveServicesCredentials
为订阅密钥和搜索词创建变量。
subscription_key = "Enter your key here" subscription_endpoint = "Enter your endpoint here" search_term = "canadian rockies"
创建图像搜索客户端
创建
CognitiveServicesCredentials
的实例并使用它实例化客户端:client = ImageSearchClient(endpoint=subscription_endpoint, credentials=CognitiveServicesCredentials(subscription_key))
向必应图像搜索 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!")