Query Images from Bing in C#

14 Sep

Microsoft Cognitive Services API’s have a variety of useful functions available.  Bing Image Search is an API which has been around for a while, but was recently revamped and merged into Cognitive Services.

Before you can do anything with the API you’ll need to get a free API key at https://www.microsoft.com/cognitive-services/en-us/bing-image-search-api

The image search API lets you do basic queries and specify desired image sizes, but it also has a few advanced query patterns that are extremely useful.  First lets take a look at a simple method you can use to query the API.  This method handles making the query, parsing the results and downloading an image to disk.

Note the query parameters we include in this example

queryString["q"] = string.Format("{0}", "grumpy cat");
queryString["count"] = "10";
queryString["offset"] = "0";
queryString["mkt"] = "en-us";
queryString["safeSearch"] = "Moderate";
queryString["size"] = "large";

We query for images matching grumpy cat which are also considered moderately safe from adult content, and of large size.  This is the first result the method will download.

grumpy

But watch what happens if we add one more query parameter

queryString["color"] = "Green"

Now we’ll get this as our first result:

image

Pretty cool huh? The images have all been filtered for their primary color, and we only get results which match our query for green images.

Now try adding this parameter instead:

queryString["imageContent"] = "Face"

Cognitive Services will apply an algorithm to find images specifically with human faces in them (we can use ‘Portrait’ if we want pictures with head and shoulders included).

face

You can find the full list of parameters on MSDN.

Go forth and find images!

Tweet about this on TwitterShare on Google+Share on FacebookShare on RedditEmail this to someoneShare on LinkedInShare on StumbleUpon

Leave a Reply

Your email address will not be published. Required fields are marked *