Quickstart: Use the Bing Image Search client library
Warning
On October 30, 2020, the Bing Search APIs moved from Azure AI services to Bing Search Services. This documentation is provided for reference only. For updated documentation, see the Bing search API documentation. For instructions on creating new Azure resources for Bing search, see Create a Bing Search resource through the Azure Marketplace.
Use this quickstart to make your first image search using the Bing Image Search client library.
The client search library is a wrapper for the REST API and contains the same features.
You'll create a C# application sends an image search query, parses the JSON response, and displays the URL of the first image returned.
Prerequisites
- If you're using Windows, any edition of Visual Studio 2017 or later
- If you're using macOS or Linux, VS Code with .NET Core installed
- A free Azure subscription
See also Azure AI services pricing - Bing Search API.
Create a console project
First, create a new C# console application.
Create a new console solution named BingImageSearch in Visual Studio.
Add the Cognitive Image Search NuGet package
- Right-click your project in Solution Explorer.
- Select Manage NuGet Packages.
- Search for and select Microsoft.Azure.CognitiveServices.Search.ImageSearch, and then install the package.
Initialize the application
Replace all of the
using
statements in Program.cs with the following code:using System; using System.Linq; using Microsoft.Azure.CognitiveServices.Search.ImageSearch; using Microsoft.Azure.CognitiveServices.Search.ImageSearch.Models;
In the
Main
method of your project, create variables for your valid subscription key, the image results to be returned by Bing, and a search term. Then instantiate the image search client using the key.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)); }
Send a search query using the client
Still in the Main
method, use the client to search with a query text:
// make the search request to the Bing Image API, and get the results"
imageResults = await client.Images.SearchAsync(query: searchTerm).Result; //search query
Parse and view the first image result
Parse the image results returned in the response.
If the response contains search results, store the first result and print out some of its details.
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();
}
Next steps
See also
Use this quickstart to make your first image search using the Bing Image Search client library, which is a wrapper for the API and contains the same features. This simple Java application sends an image search query, parses the JSON response, and displays the URL of the first image returned.
Prerequisites
The latest version of the Java Development Kit (JDK)
Install the Bing Image Search client library dependencies by using Maven, Gradle, or another dependency management system. The Maven POM file requires the following declaration:
<dependencies>
<dependency>
<groupId>com.microsoft.azure.cognitiveservices</groupId>
<artifactId>azure-cognitiveservices-imagesearch</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
Create and initialize the application
Create a new Java project in your favorite IDE or editor, and add the following imports to your class implementation:
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;
In your main method create variables for your subscription key, and search term. Then instantiate the Bing Image Search client.
final String subscriptionKey = "COPY_YOUR_KEY_HERE"; String searchTerm = "canadian rockies"; //Image search client BingImageSearchAPI client = BingImageSearchManager.authenticate(subscriptionKey);
Send a search request to the API
Using
bingImages().search()
, send the HTTP request containing the search query. Save the response as aImagesModel
.ImagesModel imageResults = client.bingImages().search() .withQuery(searchTerm) .withMarket("en-us") .execute();
Parse and view the result
Parse the image results returned in the response. If the response contains search results, store the first result and print out its details, such as a thumbnail URL, the original URL, along with the total number of returned images.
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!");
}
Next steps
See also
Use this quickstart to make your first image search using the Bing Image Search client library, which is a wrapper for the API and contains the same features. This simple JavaScript application sends an image search query, parses the JSON response, and displays the URL of the first image returned.
Prerequisites
- The latest version of Node.js.
- The Bing Image Search SDK for JavaScript
- To install, run
npm install @azure/cognitiveservices-imagesearch
- To install, run
- The
CognitiveServicesCredentials
class from@azure/ms-rest-azure-js
package to authenticate the client.- To install, run
npm install @azure/ms-rest-azure-js
- To install, run
Create and initialize the application
Create a new JavaScript file in your favorite IDE or editor, and set the strictness, https, and other requirements.
'use strict'; const ImageSearchAPIClient = require('@azure/cognitiveservices-imagesearch'); const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
In the main method of your project, create variables for your valid subscription key, the image results to be returned by Bing, and a search term. Then instantiate the image search client using the key.
//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);
Create an asynchronous helper function
Create a function to call the client asynchronously, and return the response from the Bing Image Search service.
// a helper function to perform an async call to the Bing Image Search API const sendQuery = async () => { return await imageSearchApiClient.imagesOperations.search(searchTerm); };
Send a query and handle the response
Call the helper function and handle its
promise
to parse the image results returned in the response.If the response contains search results, store the first result and print out its details, such as a thumbnail URL, the original URL, along with the total number of returned images.
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))
Next steps
See also
Use this quickstart to make your first image search using the Bing Image Search client library, which is a wrapper for the API and contains the same features. This simple Python application sends an image search query, parses the JSON response, and displays the URL of the first image returned.
Prerequisites
The Azure Image Search client library for Python
- Install using
pip install azure-cognitiveservices-search-imagesearch
- Install using
Create and initialize the application
Create a new Python script in your favorite IDE or editor, and the following imports:
from azure.cognitiveservices.search.imagesearch import ImageSearchClient from msrest.authentication import CognitiveServicesCredentials
Create variables for your subscription key and search term.
subscription_key = "Enter your key here" subscription_endpoint = "Enter your endpoint here" search_term = "canadian rockies"
Create the image search client
Create an instance of
CognitiveServicesCredentials
, and use it to instantiate the client:client = ImageSearchClient(endpoint=subscription_endpoint, credentials=CognitiveServicesCredentials(subscription_key))
Send a search query to the Bing Image Search API:
image_results = client.images.search(query=search_term)
Process and view the results
Parse the image results returned in the response.
If the response contains search results, store the first result and print out its details, such as a thumbnail URL, the original URL, along with the total number of returned images.
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!")