Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.