Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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