Azure Function to create thumbnail images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"frameworks": { | |
"net46":{ | |
"dependencies": { | |
"ImageResizer": "4.1.9" | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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