Skip to content

Instantly share code, notes, and snippets.

@stefangordon
Created September 14, 2016 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefangordon/7735fa09435b7b5c069e3a0acff7e8b6 to your computer and use it in GitHub Desktop.
Save stefangordon/7735fa09435b7b5c069e3a0acff7e8b6 to your computer and use it in GitHub Desktop.
static async void FindAndRetrieveImage()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", <AppId Goes Here>);
// Request parameters
queryString["q"] = string.Format("{0}", "grumpy cat");
queryString["count"] = "10";
queryString["offset"] = "0";
queryString["mkt"] = "en-us";
queryString["safeSearch"] = "Moderate";
queryString["size"] = "large";
//queryString["color"] = "Green";
//queryString["imageContent"] = "Face";
var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?" + queryString;
// Make the query
var response = await client.GetAsync(uri);
string content = await response.Content.ReadAsStringAsync();
// Fabricate a quick anonymous type and deserialize to it
var responseType = new { value = new[] { new { contentUrl = "", width = 0, height = 0 } } };
var results = JsonConvert.DeserializeAnonymousType(content, responseType);
// Grab results you want
var firstResult = results.value.First().contentUrl;
// Download the image
WebClient webClient = new WebClient();
using (var imageStream = new MemoryStream(webClient.DownloadData(firstResult)))
{
Image image = Image.FromStream(imageStream);
// Make any adjustments to size/format/etc here
image.Save("image.jpg", ImageFormat.Jpeg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment