Skip to content
Demonstrates how to use the Azure Storage SDK to implement a Blob trigger function to resize images in Node.js
Branch: master
Clone or download
Latest commit d6db559 Feb 12, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Initial commit Apr 6, 2018
Thumbnail Fix code for event grid trigger Feb 8, 2019
.gitignore Add extension metadata Sep 24, 2018
CHANGELOG.md Initial commit Apr 6, 2018
CONTRIBUTING.md Initial commit Apr 6, 2018
LICENSE.md Initial commit Apr 6, 2018
README.md updated readme to reflect code changes Feb 11, 2019
extensions.csproj Add extension metadata Sep 24, 2018
host.json Initial commit Apr 6, 2018
package-lock.json Initial commit Apr 6, 2018
package.json Initial commit Apr 6, 2018

README.md

Azure Storage Blob Trigger Image Resize Function in Node.js

This sample implements a function triggered by Azure Blob Storage to resize an image in Node.js. Once the image is resized, the thumbnail image is uploaded back to blob storage.

The key aspects of this sample are in the function bindings and implementation.

Function bindings

In order to interface with image data, you need to configure the function to process binary data.

The following code sets the datatype parameter to binary in the function.json file.

{
  "disabled": false,
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "myEvent",
      "direction": "in"
    },
    {
      "name": "myBlob",
      "type": "blob",
      "direction": "in",
      "path": "{data.url}",
      "connection": "AZURE_STORAGE_CONNECTION_STRING",
      "datatype": "binary"
    }
  ]
}

Function implementation

The sample uses Jimp to resize an incoming buffer to a thumbnail. The buffer is then converted to a stream (as required by createBlockBlobFromStream) and uploaded to Azure Storage.

const stream = require('stream');
const Jimp = require('jimp');

const storage = require('azure-storage');
const blobService = storage.createBlobService();

module.exports = (context, myEvent, myBlob) => {

  const widthInPixels = process.env.THUMBNAIL_WIDTH;
  const blobName = myEvent.subject.split('/')[6];

    Jimp.read(myBlob).then((thumbnail) => {

        thumbnail.resize(widthInPixels, Jimp.AUTO);

        thumbnail.getBuffer(Jimp.MIME_PNG, (err, buffer) => {

            const readStream = stream.PassThrough();
            readStream.end(buffer);

            blobService.createBlockBlobFromStream('thumbnails', blobName, readStream, buffer.length, (err) => {
                context.done();
            });
        });

    }).catch(context.log);
};

You can use the Azure Storage Explorer to view blob containers and verify the resize is successful.

You can’t perform that action at this time.