Skip to content

Instantly share code, notes, and snippets.

Last active April 16, 2020 17:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwiedemeyer/5f7da3e1fb4b4a0ac21b732746154446 to your computer and use it in GitHub Desktop.
Save mwiedemeyer/5f7da3e1fb4b4a0ac21b732746154446 to your computer and use it in GitHub Desktop.
Azure Function to create thumbnail images
"frameworks": {
"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)
// Instructions to resize the blob image.
var instructions = new Instructions
Width = 350,
Height = 350,
Mode = FitMode.Max
var url = eventGridEvent["data"]["url"].ToString();
// 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"));
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";
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