In the Search category you can also find how to search Images. In this tutorial we are going to see how to use the Bing Image Search API to search images with the term Cognitive Services.
Prerequisites
To use the Bing Image Search API you need to create a Cognitive Services API account with access to the Bing Search APIs. If you don’t have an Azure subscription, you can create a free account.
Make a request to the Bing Image Search API
The Bing Image Search API returns image results from the Bing search engine.
Create a new Console solution in Visual Studio 2017
Add the code below to the Program.cs file
class Program { // Replace this string value with your valid access key. const string subscriptionKey = "Enter your subscription key here"; // Verify the endpoint URI. If you encounter unexpected authorization errors, // double-check this value against the Bing search endpoint in your Azure dashboard. const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/images/search"; const string searchTerm = "cognitive services"; // A struct to return image search results seperately from headers struct SearchResult { public string jsonResult; public Dictionary<String, String> relevantHeaders; } static void Main() { Console.OutputEncoding = System.Text.Encoding.UTF8; Console.WriteLine("Searching images for: " + searchTerm + "\n"); //send a search request using the search term SearchResult result = BingImageSearch(searchTerm); //deserialize the JSON response from the Bing Image Search API dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(result.jsonResult); var firstJsonObj = jsonObj["value"][0]; Console.WriteLine("Title for the first image result: " + firstJsonObj["name"] + "\n"); //After running the application, copy the output URL into a browser to see the image. Console.WriteLine("URL for the first image result: " + firstJsonObj["webSearchUrl"] + "\n"); Console.Write("\nPress Enter to exit "); Console.ReadLine(); } /// <summary> /// Performs a Bing Image search and return the results as a SearchResult. /// </summary> static SearchResult BingImageSearch(string searchQuery) { // Construct the URI of the search request var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery); // Perform the Web request and get the response WebRequest request = WebRequest.Create(uriQuery); request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey; HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result; string json = new StreamReader(response.GetResponseStream()).ReadToEnd(); // Create result object for return var searchResult = new SearchResult() { jsonResult = json, relevantHeaders = new Dictionary<String, String>() }; // Extract Bing HTTP headers foreach (String header in response.Headers) { if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-")) searchResult.relevantHeaders[header] = response.Headers[header]; } return searchResult; } }
Enter your subscription key in the subscriptionKey variable.
Run the program.
The program will print out the first result. The json result is like the following or similar:
{ "_type": "Images", "instrumentation": { "pageLoadPingUrl": null }, "webSearchUrl": "https://www.bing.com/images/search?q=cognitive services&FORM=OIIARP", "totalEstimatedMatches": 810, "value": [ { "name": "Microsoft announces new Custom Cognitive Services at Build ...", "datePublished": "2017-09-03T11:11:00Z", "homePageUrl": null, "contentSize": "384050 B", "hostPageDisplayUrl": "https://www.onmsft.com/news/microsoft-announces-new-custom...", "width": 1032, "height": 580, "thumbnail": { "width": 474, "height": 266 }, "imageInsightsToken": "ccid_ZADWPXHH*mid_B1BBA86CE9CC55ABDFB65FFABF92D979BF235647*simid_608010133037450667*thid_OIP.ZADWPXHH1VvLoYJm9CVdJgHaEK", "insightsSourcesSummary": null, "imageId": "B1BBA86CE9CC55ABDFB65FFABF92D979BF235647", "accentColor": "0D75BE", "webSearchUrl": "https://www.bing.com/images/search?view=detailv2&FORM=OIIRPO&q=cognitive+services&id=B1BBA86CE9CC55ABDFB65FFABF92D979BF235647&simid=608010133037450667", "thumbnailUrl": "https://tse3.mm.bing.net/th?id=OIP.ZADWPXHH1VvLoYJm9CVdJgHaEK&pid=Api", "encodingFormat": "png", "contentUrl": "https://www.onmsft.com/wp-content/uploads/2017/05/Cog-Serv-1032x580.png" }, { "name": "Innovative IT technologies, Integration, BPM | BlueSoft", "datePublished": "2018-07-07T08:39:00Z", "homePageUrl": null, "contentSize": "27642 B", "hostPageDisplayUrl": "https://bluesoft.net.pl/en/technologies", "width": 445, "height": 378, "thumbnail": { "width": 445, "height": 378 }, "imageInsightsToken": "ccid_vuH61zRv*mid_F55D56F8AB92B8F988D658A337CF3ADC3A1B689A*simid_608014402272692166*thid_OIP.vuH61zRvXXLnYUgQUyhxYAAAAA", "insightsSourcesSummary": null, "imageId": "F55D56F8AB92B8F988D658A337CF3ADC3A1B689A", "accentColor": "8BBF0C", "webSearchUrl": "https://www.bing.com/images/search?view=detailv2&FORM=OIIRPO&q=cognitive+services&id=F55D56F8AB92B8F988D658A337CF3ADC3A1B689A&simid=608014402272692166", "thumbnailUrl": "https://tse1.mm.bing.net/th?id=OIP.vuH61zRvXXLnYUgQUyhxYAAAAA&pid=Api", "encodingFormat": "gif", "contentUrl": "https://bluesoft.net.pl/wp-content/uploads/2018/02/ms-cognitive-services-en.gif" }, ... ...
That is it! You have a working image search program! You can download the source code from my github here.