Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Azure Function to create thumbnail images
{
"frameworks": {
"net46":{
"dependencies": {
"ImageResizer": "4.1.9"
}
}
}
}
#r "Microsoft.WindowsAzure.Storage"
#r "Newtonsoft.Json"
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using ImageResizer;
using ImageResizer.ExtensionMethods;
static string s_storageAccountConnectionString = System.Environment.GetEnvironmentVariable("blogBlobImageStorage");
public static async Task Run(JObject eventGridEvent, TraceWriter log)
{
log.Info(eventGridEvent.ToString(Formatting.Indented));
// Instructions to resize the blob image.
var instructions = new Instructions
{
Width = 350,
Height = 350,
Mode = FitMode.Max
};
var url = eventGridEvent["data"]["url"].ToString();
if(url.Contains("_thumb.jpg"))
return;
// Get the blobname from the event's JObject.
var blobName = GetBlobNameFromUrl(url);
// Retrieve storage account from connection string.
var storageAccount = CloudStorageAccount.Parse(s_storageAccountConnectionString);
// Create the blob client.
var blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
var container = blobClient.GetContainerReference("blog");
// Create reference to a blob named "blobName".
var blockBlob = container.GetBlockBlobReference(blobName);
var inputStream = await blockBlob.OpenReadAsync();
var blockBlobThumb = container.GetBlockBlobReference(blobName.Replace(".jpg","_thumb.jpg"));
if(blockBlobThumb.Exists())
return;
using(MemoryStream myStream = new MemoryStream())
{
// Resize the image with the given instructions into the stream.
ImageBuilder.Current.Build(new ImageJob(inputStream, myStream, instructions));
// Reset the stream's position to the beginning.
myStream.Position = 0;
// Write the stream to the new blob.
await blockBlobThumb.UploadFromStreamAsync(myStream);
}
blockBlobThumb.Properties.ContentType = "image/jpeg";
blockBlobThumb.SetProperties();
}
private static string GetBlobNameFromUrl(string bloblUrl)
{
var myUri = new Uri(bloblUrl);
var myCloudBlob = new CloudBlob(myUri);
return myCloudBlob.Name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment