Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nikneem
Created December 23, 2019 15:06
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 nikneem/f808784b63530cd41200a5086942b5c1 to your computer and use it in GitHub Desktop.
Save nikneem/f808784b63530cd41200a5086942b5c1 to your computer and use it in GitHub Desktop.
public static class CognitiveServicesFunction
{
private static string subscriptionKey = Environment.GetEnvironmentVariable("COMPUTER_VISION_SUBSCRIPTION_KEY");
private static string endpoint = Environment.GetEnvironmentVariable("COMPUTER_VISION_ENDPOINT");
private static string uriBase = endpoint + "vision/v2.1/analyze";
[FunctionName("CognitiveServicesFunction")]
public static async Task Run(
[BlobTrigger("scaled-images/{name}", Connection = "")] CloudBlockBlob blob,
string name,
ILogger log)
{
log.LogInformation($"Incoming scaled image, going to analyse it using cognitive services");
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
await blob.FetchAttributesAsync();
long fileByteLength = blob.Properties.Length;
byte[] fileContent = new byte[fileByteLength];
string uri = $"{uriBase}?visualFeatures=Categories,Description,Color";
var downloaded = await blob.DownloadToByteArrayAsync(fileContent, 0);
using (ByteArrayContent content = new ByteArrayContent(fileContent))
{
content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
var response = await httpClient.PostAsync(uri, content);
string contentString = await response.Content.ReadAsStringAsync();
Console.WriteLine("\nResponse:\n\n{0}\n",
JToken.Parse(contentString).ToString());
}
await blob.DeleteIfExistsAsync();
}
catch (Exception e)
{
Console.WriteLine("\n" + e.Message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment