Wednesday, June 15, 2022

BlobTrigger in azure function ,Resize files after uploading in blob

 In previous post we saw how to create azure function for HttpTrigger. Now lets see another use of azure function.

Scenario - Suppose you are uploading file in blob either directly from azure portal or through .net code and after upload you want to create thumbnail or resize that file . For this if you will do during upload in .net code then it might take time and user will not be happy with system performance . So to tackle such kind of scenario azure has provided BlobTrigger function. which automatically trigger and resize your file after uploading in blob. if you want to know more about azure function from start please see the previous post.

So Lets see how we can achieve this.

1. Open Visual Studio -> Create New Project -> Search for Azure functions Templates and click Next

1.Enter project name “AzureFunBlobTrigger” and click Next

2.In next section you need to select Trigger Type ,so select Blob Trigger and keep storage emulator in right side , if you want to use azure storage you can browse and choose.



in Solution explorer you will see below




Local.settings.json : In this file configure storage account and runtime framework. It has key-value code. open this file and paste the below code

{

    "IsEncrypted": false,

  "Values": {

    "AzureWebJobsStorage": "your storgate connection string",

    "FUNCTIONS_WORKER_RUNTIME": "dotnet",

    "fnBlob": "your storgate connection string"

  }

}

fnBlob is the key which you are going to use for blob connection.

Function1.cs: Open the function.cs and paste the below code

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System.IO;

namespace AzureFunBlobTrigger
{
    public static class Function1
    {
        [FunctionName("Function1")]
         public static void Run(
               [BlobTrigger("mycontainer/{name}", Connection = "fnBlob")] Stream inputBlob, string name,
               [Blob("resized/{name}", FileAccess.Write, Connection = "fnBlob")] Stream outputBlob, TraceWriter log)
        {
            log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {inputBlob.Length} Bytes");
         
            ResizeImage( inputBlob, outputBlob, 300,150);
         
        }
        private static void ResizeImage(Stream input, Stream output, int width,int height)
        {
            using (Image image = Image.Load(input))
            {
                image.Mutate(x => x
                        .Resize(new ResizeOptions
                        {
                            Mode = ResizeMode.BoxPad,
                            Size = new Size(width, height) // you can define size what u need
                        }).BackgroundColor(new Rgba32(0, 0, 0)));

                image.Save(output, new JpegEncoder());
            }
        }

    }
}


L Lets understand the below code block

[FunctionName("Function1")]
         public static void Run(
               [BlobTrigger("mycontainer/{name}", Connection = "fnBlob")] Stream myBlob, string name,
               [Blob("resized/{name}", FileAccess.Write, Connection = "fnBlob")] Stream outputBlob, TraceWriter log)


     [FunctionName("Function1")] - function name which you can change with any name .

   [BlobTrigger("mycontainer/{name}" -BlobTrigger is the attribute which trigger the function when any file will get upload in container "mycontainer".

    Connection = "fnBlob")] - storage connection string name which I have defined in local.setting.json

    [Blob("resized/{name}", another container where file will be save after resizing. you dont need to create ,it will be automatically created if not.

   In the above code I have created one function called ResizeImage where I am passing input blob(which has been uploaded ,output blob path and name , size.

   To resize image I am using nuget package called SixLabors.ImageSharp which you can add from package manager. I found this package more clean ,fast and easy to implement.

   Thats all about coding part.

   Lets try to upload file in container from azure portal and see what happens

L   1. Login to azure portal and go to storage account -> container -> mycontainer -> select upload and upload one file. as soon as you upload your file automatically your function will trigger in your local visual studio and resize the file and save in the output folder.

    Before that just run your project from visual studio . you will see below logs if your function run successfully in vs.

   Now let put our debugger in code just to make sure our function is triggered after uploading image in blob.


Now go to mycontainer and upload one image and you will see your local function got triggered.
   


   now you can see your function gets trigger in the code and resize uploaded image and push to resized container.

   This is the resized container.


   We are done with blob trigger azure function and this might be the real case for you where you can use azure function  ..

   Thanks and good luck.


No comments:

Post a Comment

Thanks for your valuable comments

Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function ( httpTrigger ) and send html content  which will be converted into PDF and save in bl...