Building an Azure Serverless Function for image processing

Azure functions are an excellent solution for serverless computing needs. They’re highly scalable, flexible, and can handle complex business logic that runs asynchronously. In this tutorial, we’ll dive into how to build an Azure function for image processing using Azure Functions.

What is Azure Functions?

Azure Functions is a serverless computing platform that allows you to write event-driven functions that execute when triggered by an event. These functions can be written in various programming languages, including C#, F#, Java, Python, and Node.js and execute in a fully managed, serverless environment.

Azure Functions scale seamlessly based on demand, which makes them an excellent solution for applications with unpredictable traffic. They also allow you to save money by only paying for the processing power used, rather than paying for idle servers and infrastructure.

Azure Functions Prerequisites

Before we dive into building our Azure function for image processing, we need to have a few prerequisites in place.

Azure Subscription

First, we need to have an Azure subscription. If you don’t have an Azure subscription, you can sign up for a free one-month trial and get $200 in free Azure credits to try the service.

Azure Functions Core Tools

Second, we need to download and install the Azure Functions Core Tools. The Azure Functions Core Tools has everything we need to develop, test, and deploy Azure Functions locally.

You can download the Azure Functions Core Tools from the official GitHub page.

Azure Storage Account

We also need to create an Azure Storage account to store the data generated by our Azure function. Azure Functions use the Azure Storage account to store logs, function code, and other assets.

Azure Computer Vision API Key

We will use the Azure Computer Vision API to process the images. We need to obtain an Azure Computer Vision API Key to use the service. We can create an Azure Computer Vision API account through the Azure portal.

Creating the Azure Function

Now that we have the prerequisites in place, we can start building our Azure function.

  1. Open your terminal or command prompt and type the following command to create a new Azure function project.
func init image-processor --worker-runtime node 

This command creates a new Azure function project with Node.js as a runtime.

  1. Change the current directory to the image-processor directory.
cd image-processor
  1. Use the following command to create a new Azure function.
func new --name image-processor --template "HttpTrigger"

This command creates a new Azure function with an HTTP trigger. This trigger allows us to call the function through an HTTP endpoint, which passes the image URL to our function.

  1. Install the following NPM packages that we need to perform image processing.
npm install azure-storage
npm install request

Writing the Azure Function

Now that we’ve created our Azure function project, let’s dive into writing the actual Azure function.

  1. Open the image-processor/index.js file in your preferred IDE or text editor.
  2. Add the following code to your index.js file to import required modules.

const request = require("request");
const azure = require('azure-storage');
const visionApiKey = process.env['COMPUTER_VISION_API_KEY'];
const blobService = azure.createBlobService()

The code imports the request module that we will use to send requests to the Azure computer vision API and the azure-storage module. We then define the Azure Computer Vision API key as an environment variable and create a new blob service instance to perform operations on the Azure storage account.

  1. Replace the existing function code with the following code.
module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    let responseHeaders = { 'Content-Type': 'application/json' };
    if (req.body.url) {
        const url = req.body.url.trim();
        request.post({
            url: "https://westus2.api.cognitive.microsoft.com/vision/v2.0/analyze?visualFeatures=Description",
            headers: {
                "Content-Type": "application/json",
                "Ocp-Apim-Subscription-Key": visionApiKey
            },
            json: {
                url: url
            }
        }, function (err, httpResponse, body) {
            if (err) {
                context.log.error(err);
                context.res = {
                    headers: responseHeaders,
                    body: JSON.stringify({ error: err })
                };
                context.done();
                return;
            }
            if (body.error) {
                context.log.error(body.error.message);
                context.res = {
                    headers: responseHeaders,
                    body: JSON.stringify({ error: body.error })
                };
                context.done();

          return;
            }
            const connString = process.env['AzureWebJobsStorage'];
            const containerName = "images"
            const blobName = Date.now() + ".json";
            const blobUrl = `https://${connString}.blob.core.windows.net/${containerName}/${blobName}`
            const blobContent = JSON.stringify(body)
            blobService.createBlockBlobFromText(containerName, blobName, blobContent, function (error, result, response) {
                if (error) {
                    context.log.error(`Failed to store JSON. ${error}`);
                    context.res = {
                        headers: responseHeaders,
                        body: JSON.stringify({ error: error })
                    };
                } else {
                    context.res = {
                        headers: responseHeaders,
                        body: JSON.stringify({ result: { 'url': url, 'visionResultUrl': blobUrl } })
                    };
                }
                context.done();
            });
        });
    } else {
        context.res = {
            headers: responseHeaders,
            body: JSON.stringify({ error: 'URL is not defined.' })
        };
        context.done();
    }
};

This code defines the image-processing Azure function. The function accepts an HTTP request with a URL of the image to process. The code sends a request to Azure computer vision API to analyze the image and generate a JSON response containing information about the image, such as its description.

The code then saves the JSON to the Azure Storage account and returns the URL of the JSON file.

Deploying the Azure Function

Now that we have written our Azure function, we can deploy it to Azure.

  1. Open your terminal or command prompt and change the directory to your project’s root folder.
  2. Use the following command to publish your function to Azure.

func azure functionapp publish <function-app-name> --build remote

The command publishes the code to Azure and compiles it remotely. The is the name of the Azure function app you created in the Azure portal.

  1. Navigate to the Azure portal to verify that the function is working correctly.

Testing the Azure Function

Now that we have deployed our function to Azure, we can test it by invoking the HTTP endpoint.

  1. Open Postman or your favorite REST client.
  2. Create a new POST request and enter the HTTP endpoint of your Azure function.

  3. In the request body, enter the following JSON.

{
    "url": "<image-url>"
}

Replace “” with the URL of an image you’d like to process. An excellent source of images to use for testing is the following URL: https://pixabay.com/api/docs.

  1. Send the request and verify that the JSON file is stored in the Azure Storage account.

Conclusion

In this tutorial, we learned how to build an Azure function for image processing using Azure Functions. We started by creating the Azure function project, writing the Azure function, deploying it to Azure, and testing it using an HTTP endpoint.

Azure Functions allow you to scale your applications seamlessly based on demand and are an excellent solution for applications with unpredictable traffic. By only paying for the processing power used, Azure Functions enable you to save money on infrastructure costs.

Related Post