Getting Started With Bing Image Search API

In this tutorial, we will learn how to use Bing Image Search API. Remember, in our first example of cognitive services, we had created a demo Bing Speech API. In this tutorial, we will extend the same demo to search images, i.e., we will pass the text result of Bing Speech API to Bing Image Search API. Yes, and we will call the cognitive service using HTTPS REST, like we are calling normal HTTPS Web Services. In our first example of Bing Speech API, we used .NET Client Library to make REST call of API for the ease in .NET. All the cognitive services are HTTPS REST APIs that can be called using any language which makes an HTTPS call. If you have missed part 1 of this series, you can find it here.

To register for Bing Image Search API follow these steps.

  1. Navigate to https://azure.microsoft.com/en-us/try/cognitive-services/
  2. Navigate to the "Search" tab and select Bing Search API. Then, press "Get API Key".

    Azure

  3. Select "I agree" and your region, as shown in the following image.

    Azure

  4. Login with Microsoft account to get your API key.

    Azure

  5. Save your key.

    Azure

Now, it’s time to recall part 1 in which we covered "Speech to Text" (STT) using Bing Speech API. We will simply use its result as input for Bing Image Search API.

  1. private async void MicClient_OnResponseReceived(object sender, SpeechResponseEventArgs e)  
  2.         {  
  3.             if (e.PhraseResponse.Results.Length > 0)  
  4.             {  
  5.                 await Application.Current.Dispatcher.BeginInvoke(  
  6.                     DispatcherPriority.Normal, new Action(() =>  
  7.                     {  
  8.                         this.MySpeechResponse.Text = $"'{e.PhraseResponse.Results[0].DisplayText}',";  
  9.                         this.MySpeechResponseConfidence.Text = $"confidence: { e.PhraseResponse.Results[0].Confidence}";  
  10.                           
  11.                         //this.Speak(this.MySpeechResponse.Text);  
  12.                     }));  
  13. this.SearchImage(e.PhraseResponse.Results[0].DisplayText);  
  14.             }  
  15.         }  

Here, in "onResponseReceived" method, we will get the text of what we have spoken. Now, we will use that text as input for Bing Image Search API, as shown in the below code.

  1. private async void SearchImage(string SearchTerm)  
  2.         {  
  3.             var client = new HttpClient();  
  4.             var queryString = HttpUtility.ParseQueryString(string.Empty);  
  5.   
  6.             // Request headers  
  7.             client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""Your_key_Bing_Image_Search_API");  
  8.   
  9.             // Request parameters  
  10.             queryString["q"] = SearchTerm;  
  11.             queryString["count"] = "1";  
  12.             queryString["offset"] = "0";  
  13.             queryString["mkt"] = "en-us";  
  14.             queryString["safeSearch"] = "Moderate";  
  15.             var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?" + queryString;  
  16.   
  17.             var response = await client.GetAsync(uri);  
  18.             var json = await response.Content.ReadAsStringAsync();  
  19.            // MessageBox.Show(json.ToString());  
  20.             BingImageSearchResponse bingImageSearchResponse = JsonConvert.DeserializeObject<BingImageSearchResponse>(json);  
  21.             var uriSource = new Uri(bingImageSearchResponse.value[0].contentUrl, UriKind.Absolute);  
  22.   
  23.             await Application.Current.Dispatcher.BeginInvoke(  
  24.                 DispatcherPriority.Normal, new Action(() =>  
  25.                 {  
  26.                     this.searchImage.Source = new BitmapImage(uriSource);  
  27.   
  28.                 }));  
  29.         }  

The above method is simply making HTTPS REST request to API (that means it is not necessary for anyone to use Cognitive Services only in WPF application or by using C# language, one can use it with any other language too) and it will result in a JSON response.

Now, let’s perform the following steps to implement Bing Image Search API. First, download part 1 from here.

  1. First, add an Image tag in MainWindow.xaml or simply replace the code between <Grid></Grid> with the given code.
    1. <Grid>  
    2.         <Grid.RowDefinitions>  
    3.             <RowDefinition Height="Auto"></RowDefinition>  
    4.             <RowDefinition Height="Auto"></RowDefinition>  
    5.             <RowDefinition Height="Auto"></RowDefinition>  
    6.             <RowDefinition Height="Auto"></RowDefinition>  
    7.             <RowDefinition Height="*"></RowDefinition>  
    8.         </Grid.RowDefinitions>  
    9.         <Grid.ColumnDefinitions>  
    10.             <ColumnDefinition Width="Auto"></ColumnDefinition>  
    11.             <ColumnDefinition Width="*"></ColumnDefinition>  
    12.             <ColumnDefinition Width="3*"></ColumnDefinition>  
    13.         </Grid.ColumnDefinitions>  
    14.         <TextBlock FontSize="24" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Margin="4">Bing Speech API with Image Search</TextBlock>  
    15.         <Button x:Name="button" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Click="button_Click"  
    16.                 Grid.Row="1" Grid.Column="0" Grid.RowSpan="3" Margin="4" Height="75">  
    17.             <Button.Content>  
    18.                 <StackPanel Orientation="Vertical">  
    19.                     <TextBlock FontSize="16">Speak</TextBlock>  
    20.                 </StackPanel>  
    21.             </Button.Content>  
    22.         </Button>  
    23.   
    24.         <TextBlock x:Name="status" TextWrapping="Wrap" Text="Not Listening" VerticalAlignment="Center" FontSize="16" Visibility="Collapsed"  
    25.                    Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" Margin="4"/>  
    26.   
    27.         <StackPanel Orientation="Horizontal" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2">  
    28.             <TextBlock x:Name="MySpeechResponse" FontSize="20" Margin="4" TextWrapping="Wrap" VerticalAlignment="Center" />  
    29.             <TextBlock x:Name="MySpeechResponseConfidence" FontSize="12" Margin="4" TextWrapping="Wrap" VerticalAlignment="Center" />  
    30.         </StackPanel>  
    31.         <Image x:Name="searchImage" Margin="4" Stretch="Uniform"  
    32.                Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="3"/>  
    33.   
    34.   
    35.         <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="RecordingBar" Visibility="Collapsed"  
    36.                     Grid.Row="0" Grid.Column="0" Grid.RowSpan="5" Grid.ColumnSpan="3">  
    37.   
    38.             <ProgressBar HorizontalAlignment="Left" Width="207" Margin="0,16,0,0" IsIndeterminate="True" />  
    39.         </StackPanel>  
    40.   
    41.     </Grid>  
  1. Then, inside Solution Explorer, right click your project and click "Manage NuGet Packages".

    Azure

  2. Inside NuGet Package Manager window, navigate to the "Browse" tab and search for Newtonsoft.Json.

    Azure

  3. Also, right click on "References" and reference the System.Web.

    Azure

  4. Create a class or data structure to store the JSON result as per your need (optional).
    1. using System;  
    2.   
    3. public class BingImageSearchResponse  
    4. {  
    5.     public string _type { get; set; }  
    6.     public string readLink { get; set; }  
    7.     public string webSearchUrl { get; set; }  
    8.     public string webSearchUrlPingSuffix { get; set; }  
    9.     public int totalEstimatedMatches { get; set; }  
    10.     public Value[] value { get; set; }  
    11.     public int nextOffsetAddCount { get; set; }  
    12.     public bool displayShoppingSourcesBadges { get; set; }  
    13.     public bool displayRecipeSourcesBadges { get; set; }  
    14. }  
    15.   
    16. public class Value  
    17. {  
    18.     public string name { get; set; }  
    19.     public string webSearchUrl { get; set; }  
    20.     public string webSearchUrlPingSuffix { get; set; }  
    21.     public string thumbnailUrl { get; set; }  
    22.     public DateTime datePublished { get; set; }  
    23.     public string contentUrl { get; set; }  
    24.     public string hostPageUrl { get; set; }  
    25.     public string hostPageUrlPingSuffix { get; set; }  
    26.     public string contentSize { get; set; }  
    27.     public string encodingFormat { get; set; }  
    28.     public string hostPageDisplayUrl { get; set; }  
    29.     public int width { get; set; }  
    30.     public int height { get; set; }  
    31.     public string imageInsightsToken { get; set; }  
    32.     public string imageId { get; set; }  
    33.     public string accentColor { get; set; }  
    34. }  
  1. Finally, add "Search Image" method and call it to MainWindow.xaml.cs.
    1. namespace BingSpeechDemowithImageSerach  
    2. {  
    3.     using System.Media;  
    4.     using System.Threading;  
    5.     using System.Windows.Threading;  
    6.       
    7.     using Microsoft.CognitiveServices.SpeechRecognition;  
    8.     using System.Net.Http;  
    9.     using Newtonsoft.Json;  
    10.     using System.Web;  
    11.     /// <summary>  
    12.     /// Interaction logic for MainWindow.xaml  
    13.     /// </summary>  
    14.     public partial class MainWindow : Window  
    15.     {  
    16.         private MicrophoneRecognitionClient micClient;  
    17.         public MainWindow()  
    18.         {  
    19.             InitializeComponent();  
    20.             this.micClient = SpeechRecognitionServiceFactory.CreateMicrophoneClient(  
    21.                 SpeechRecognitionMode.ShortPhrase,  
    22.                 "en-US",  
    23.                 "Your_Bing_Speech_API_KEY");  
    24.             this.micClient.OnMicrophoneStatus += MicClient_OnMicrophoneStatus;  
    25.             this.micClient.OnResponseReceived += MicClient_OnResponseReceived;  
    26.         }  
    27.   
    28.         private void button_Click(object sender, RoutedEventArgs e)  
    29.         {  
    30.             this.MySpeechResponse.Text = string.Empty;  
    31.             this.MySpeechResponseConfidence.Text = string.Empty;  
    32.             this.searchImage.Source = null;  
    33.             this.micClient.StartMicAndRecognition();  
    34.         }  
    35.   
    36.         private void MicClient_OnMicrophoneStatus(object sender, MicrophoneEventArgs e)  
    37.         {  
    38.             Application.Current.Dispatcher.BeginInvoke(  
    39.                 DispatcherPriority.Normal,  
    40.                 new Action(  
    41.                     () =>  
    42.                     {  
    43.                         if (e.Recording)  
    44.                         {  
    45.                             this.status.Text = "Listening";  
    46.                             this.RecordingBar.Visibility = Visibility.Visible;  
    47.                         }  
    48.                         else  
    49.                         {  
    50.                             this.status.Text = "Not Listening";  
    51.                             this.RecordingBar.Visibility = Visibility.Collapsed;  
    52.                         }  
    53.                     }));  
    54.         }  
    55.   
    56.         private async void MicClient_OnResponseReceived(object sender, SpeechResponseEventArgs e)  
    57.         {  
    58.             if (e.PhraseResponse.Results.Length > 0)  
    59.             {  
    60.                 await Application.Current.Dispatcher.BeginInvoke(  
    61.                     DispatcherPriority.Normal, new Action(() =>  
    62.                     {  
    63.                         this.MySpeechResponse.Text = $"'{e.PhraseResponse.Results[0].DisplayText}',";  
    64.                         this.MySpeechResponseConfidence.Text = $"confidence: { e.PhraseResponse.Results[0].Confidence}";  
    65.                     }));  
    66.                 this.SearchImage(e.PhraseResponse.Results[0].DisplayText);  
    67.             }  
    68.         }  
    69.         private async void SearchImage(string phraseToSearch)  
    70.         {  
    71.             var client = new HttpClient();  
    72.             var queryString = HttpUtility.ParseQueryString(string.Empty);  
    73.   
    74.             // Request headers  
    75.             client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""Your_Key_Bing_Image_search_API_HERE");  
    76.   
    77.             // Request parameters  
    78.             queryString["q"] = phraseToSearch;  
    79.             queryString["count"] = "1";  
    80.             queryString["offset"] = "0";  
    81.             queryString["mkt"] = "en-us";  
    82.             queryString["safeSearch"] = "Moderate";  
    83.             var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?" + queryString;  
    84.   
    85.             var response = await client.GetAsync(uri);  
    86.             var json = await response.Content.ReadAsStringAsync();  
    87.             // MessageBox.Show(json.ToString());  
    88.             BingImageSearchResponse bingImageSearchResponse = JsonConvert.DeserializeObject<BingImageSearchResponse>(json);  
    89.             var uriSource = new Uri(bingImageSearchResponse.value[0].contentUrl, UriKind.Absolute);  
    90.   
    91.             await Application.Current.Dispatcher.BeginInvoke(  
    92.                 DispatcherPriority.Normal, new Action(() =>  
    93.                 {  
    94.                     this.searchImage.Source = new BitmapImage(uriSource);  
    95.   
    96.                 }));  
    97.         }  
    98.   
    99.     }  
    100. }  

Source Code

Output

Azure

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now