警告
2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅必应搜索 API 文档。 关于为必应搜索创建新的 Azure 资源的说明,请参阅通过 Azure 市场创建必应搜索资源。
请使用这一快速入门指南,通过必应图像搜索客户端库进行首次图像搜索。
客户端搜索库是 REST API 的包装器,包含相同的功能。
你将创建 C# 应用程序发送图像搜索查询,分析 JSON 响应,并显示返回的第一个图像的 URL。
先决条件
- 如果您使用的是 Windows 操作系统,则可以使用任意版本的 Visual Studio 2017 或更高版本
- 如果您使用的是 macOS 或 Linux,并且在 VS Code 上安装了 .NET Core
- 免费的 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
- 若要安装,请运行
- 用于认证客户端的
CognitiveServicesCredentials
包中的@azure/ms-rest-azure-js
类。- 若要安装,请运行
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!")