{"id":4094,"date":"2023-11-04T23:14:03","date_gmt":"2023-11-04T23:14:03","guid":{"rendered":"http:\/\/localhost:10003\/building-an-azure-serverless-function-for-image-processing\/"},"modified":"2023-11-05T05:48:01","modified_gmt":"2023-11-05T05:48:01","slug":"building-an-azure-serverless-function-for-image-processing","status":"publish","type":"post","link":"http:\/\/localhost:10003\/building-an-azure-serverless-function-for-image-processing\/","title":{"rendered":"Building an Azure Serverless Function for image processing"},"content":{"rendered":"
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.<\/p>\n
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.<\/p>\n
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.<\/p>\n
Before we dive into building our Azure function for image processing, we need to have a few prerequisites in place.<\/p>\n
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.<\/p>\n
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.<\/p>\n
You can download the Azure Functions Core Tools from the official GitHub page.<\/p>\n
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.<\/p>\n
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.<\/p>\n
Now that we have the prerequisites in place, we can start building our Azure function.<\/p>\n
func init image-processor --worker-runtime node \n<\/code><\/pre>\nThis command creates a new Azure function project with Node.js as a runtime.<\/p>\n
\n- Change the current directory to the image-processor directory.<\/li>\n<\/ol>\n
cd image-processor\n<\/code><\/pre>\n\n- Use the following command to create a new Azure function.<\/li>\n<\/ol>\n
func new --name image-processor --template \"HttpTrigger\"\n<\/code><\/pre>\nThis 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.<\/p>\n
\n- Install the following NPM packages that we need to perform image processing.<\/li>\n<\/ol>\n
npm install azure-storage\nnpm install request\n<\/code><\/pre>\nWriting the Azure Function<\/h2>\n
Now that we’ve created our Azure function project, let’s dive into writing the actual Azure function.<\/p>\n
\n- Open the image-processor\/index.js file in your preferred IDE or text editor.<\/p>\n<\/li>\n
- \n
Add the following code to your index.js file to import required modules.<\/p>\n<\/li>\n<\/ol>\n
const request = require(\"request\");\nconst azure = require('azure-storage');\nconst visionApiKey = process.env['COMPUTER_VISION_API_KEY'];\nconst blobService = azure.createBlobService()\n<\/code><\/pre>\nThe 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.<\/p>\n
\n- Replace the existing function code with the following code.<\/li>\n<\/ol>\n
module.exports = function (context, req) {\n context.log('JavaScript HTTP trigger function processed a request.');\n let responseHeaders = { 'Content-Type': 'application\/json' };\n if (req.body.url) {\n const url = req.body.url.trim();\n request.post({\n url: \"https:\/\/westus2.api.cognitive.microsoft.com\/vision\/v2.0\/analyze?visualFeatures=Description\",\n headers: {\n \"Content-Type\": \"application\/json\",\n \"Ocp-Apim-Subscription-Key\": visionApiKey\n },\n json: {\n url: url\n }\n }, function (err, httpResponse, body) {\n if (err) {\n context.log.error(err);\n context.res = {\n headers: responseHeaders,\n body: JSON.stringify({ error: err })\n };\n context.done();\n return;\n }\n if (body.error) {\n context.log.error(body.error.message);\n context.res = {\n headers: responseHeaders,\n body: JSON.stringify({ error: body.error })\n };\n context.done();\n\n return;\n }\n const connString = process.env['AzureWebJobsStorage'];\n const containerName = \"images\"\n const blobName = Date.now() + \".json\";\n const blobUrl = `https:\/\/${connString}.blob.core.windows.net\/${containerName}\/${blobName}`\n const blobContent = JSON.stringify(body)\n blobService.createBlockBlobFromText(containerName, blobName, blobContent, function (error, result, response) {\n if (error) {\n context.log.error(`Failed to store JSON. ${error}`);\n context.res = {\n headers: responseHeaders,\n body: JSON.stringify({ error: error })\n };\n } else {\n context.res = {\n headers: responseHeaders,\n body: JSON.stringify({ result: { 'url': url, 'visionResultUrl': blobUrl } })\n };\n }\n context.done();\n });\n });\n } else {\n context.res = {\n headers: responseHeaders,\n body: JSON.stringify({ error: 'URL is not defined.' })\n };\n context.done();\n }\n};\n<\/code><\/pre>\nThis 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.<\/p>\n
The code then saves the JSON to the Azure Storage account and returns the URL of the JSON file.<\/p>\n
Deploying the Azure Function<\/h2>\n
Now that we have written our Azure function, we can deploy it to Azure.<\/p>\n
\n- Open your terminal or command prompt and change the directory to your project’s root folder.<\/p>\n<\/li>\n
- \n
Use the following command to publish your function to Azure.<\/p>\n<\/li>\n<\/ol>\n
func azure functionapp publish <function-app-name> --build remote\n<\/code><\/pre>\nThe 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.<\/p>\n\n- Navigate to the Azure portal to verify that the function is working correctly.<\/li>\n<\/ol>\n
Testing the Azure Function<\/h2>\n
Now that we have deployed our function to Azure, we can test it by invoking the HTTP endpoint.<\/p>\n
\n- Open Postman or your favorite REST client.<\/p>\n<\/li>\n
- \n
Create a new POST request and enter the HTTP endpoint of your Azure function.<\/p>\n<\/li>\n
- \n
In the request body, enter the following JSON.<\/p>\n<\/li>\n<\/ol>\n
{\n \"url\": \"<image-url>\"\n}\n<\/code><\/pre>\nReplace “” 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.<\/p>\n\n- Send the request and verify that the JSON file is stored in the Azure Storage account.<\/li>\n<\/ol>\n
Conclusion<\/h2>\n
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.<\/p>\n
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.<\/p>\n","protected":false},"excerpt":{"rendered":"
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 Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[1114,585,87,30,708,1253,326,212,424,1255],"yoast_head":"\nBuilding an Azure Serverless Function for image processing - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n