Writing SQL style triggers or stitching action to events in Azure has become easier. With Function Apps, I can write a piece of code that will be triggered at a defined time or an event. Event can be a file added to OneDrive or blob storage. These Azure functions can call other Azure functions. Thus, you can upload an image to blob, and the Function can trim and insert to another blob storage.

Here’s how I did it…

Search for Function App in the marketplace.

Create your function app by providing few basic information as

Once your app is deployed and running, you can add a new function to it. Click on the app on your dashboard (if you have pinned it) and click on new function. This brings up a list of function templates. I used BlobTrigger C# template.

Once you select a template, scroll down and fill a few details. Click on new and select the storage account you used while creating the app.

Once you click create, it opens a code editor where you can add your code. However, before that we should add blob storage. For that, search for storage accounts, go to the storage we just created for this App and add two blob storages – originals and thumbnails.

 

Now go back to the Function App and click on Integrate tab. Here we will create the mapping. Trigger parameters are almost set, I however changed name.

Then I added an output parameter to tie to the thumbnail blob I created. Click on “New Output” and chose Azure Storage Blob and changed the name and path to thumbnails/{name}. Be sure to use correct name for output blob container!

 

 

Since we are going to call new Cognitive Services, we need Computer Vision API Key, and then add this code to your function.

using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;

public static void Run(Stream inputBlob, Stream thumbnailBlob, TraceWriter log)
{
    string SubscriptionKey = "YourCognitiveServiceKey";

    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", SubscriptionKey);
        using (HttpContent content = new StreamContent(inputBlob))
        {
            string url = "https://api.projectoxford.ai/vision/v1.0/generateThumbnail"
            content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/octet-stream");
            var uri = url + "?width=300&height=300&smartCropping=true";
            var response = httpClient.PostAsync(uri, content).Result;
            var responseBytes = response.Content.ReadAsByteArrayAsync().Result;

            //write to output thumb
            thumbnailBlob.Write(responseBytes, 0, responseBytes.Length);
        }
    }
}

When you save the code, you should see “Compilation succeeded” message in log. Now an upload to “original” blob should result in a thumbnail inserted to thumbnails blob!

 

 

 

Advertisements