Barcode Image Generation in Azure with Serverless Functions
This tutorial describes how to create a QR Code Serverless Function in Azure for Barcode Generation with the IDAutomation .NET Generator. Other barcode types such as GS1, PDF417, Data Matrix, and Code 128 may be also easily implemented using the same process. An Azure Function is a serverless compute service designed to simplify the development of event-driven applications by allowing developers to write and deploy code and barcode generators without managing the underlying infrastructure.
Below is a visual of the final product:
Prerequisites
- Azure Account: An Azure account with the ability to create resource groups and function apps.
- Visual Studio 2022 or greater
- .NET 6 or greater
- IDAutomation .NET Generator
1. Setting Up the Project
- Open Visual Studio 2022, select "Create a new project," and find the 'Azure Function' template. Name the project and solution.
- Choose .NET 6, HTTPTrigger, and set the authorization level to anonymous. This is to simplify for demonstration purposes, 'anonymous' is not the default recommendation.
- Run the project once to ensure successful setup.
2. Code Implementation
- In the solution explorer, right-click the 'Function1' class and rename it to 'GenerateQRCode'.
- Add the IDAutomation .NET Standard QR Code cs file to the project.
- This file can be located in "file\path\IDAutomation_DotnetStandard_QRCode\Dotnet Standard 2.0"
- Right-click the IDAutomation file, select properties, and make sure under 'Advanced' the 'Copy to Output Directory' is set to 'Newest'.
- Create a folder named 'www' and include an index.html file for the front end.
- Right-click the index.html file, select properties, and make sure under 'Advanced' the 'Copy to Output Directory' is set to 'Always'.
- Add the following code in the GenerateQRCode class:
[FunctionName("GenerateQRCode")]
public static IActionResult QRCodeGen([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log)
{
try
{
string textToEncode = req.Query["text"];
log.LogInformation("Generating QR Code for {0}", textToEncode);
QRCode qr = new();
byte[] bmpStream = qr.EncodeQR(textToEncode, true, EncodingModes.Byte, Versions.AUTO, ErrorCorrectionLevels.M, true, 1, 5);
var ourResult = new ReturnObject { };
ourResult.Image = Convert.ToBase64String(bmpStream);
return new JsonResult(ourResult);
}
catch (Exception ex)
{
log.LogError($"Error generating QR code: {ex.Message}");
log.LogError($"Hello there error is: {ex.Source}");
return new BadRequestObjectResult("Error generating QR code. Please check your input.");
}
}
public class ReturnObject
{
public string Image { get; set; }
}
- public static IActionResult QRCodeGen([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log): This method receives HTTP requests, generates a QR Code based on the provided text input, and returns the QR Code image as a Base64 string.
- req.Query["text"]: Extracts the text input from the query parameters of the HTTP request.
- QRCode qr = new();: Initializes a QRCode object from the IDAutomation library.
- byte[] bmpStream = qr.EncodeQR(...): Encodes the input text into a QR Code image byte stream.
- Convert.ToBase64String(bmpStream): Converts the byte stream of the QR Code image into a Base64 string.
- return new JsonResult(ourResult): Returns the Base64 string representation of the QR Code image as a JSON response.
3. Code for Form Generation
[FunctionName("Form")]
public static HttpResponseMessage Form(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log, ExecutionContext context)
{
string indexPage = File.ReadAllText(context.FunctionAppDirectory + "/www/index.html");
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
result.Content = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(indexPage));
return result;
}
- public static HttpResponseMessage Form(...): This method serves the HTML content of the frontend form.
- File.ReadAllText(context.FunctionAppDirectory + "/www/index.html"): Reads the content of the index.html file located in the www folder of the function app.
- HttpResponseMessage(HttpStatusCode.OK): Initializes an HTTP response message with a status code of 200 (OK).
- result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"): Sets the content type of the response to HTML.
- result.Content = new ByteArrayContent(...): Sets the HTML content of the response to the content read from the index.html file.
4. Double Check Using Statements:
using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using IDAutomation.NetStandard.QRCode.FontEncoder;
using System.Net.Http;
using System.Net;
using System.Net.Http.Headers;
5. HTML Code for Frontend (index.html):
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
padding-top: 10%;
}
</style>
</head>
<body>
<h2>QR Code Generator</h2>
<input id="inputbox" style="width: 350px;">
<br /><br />
<button type="button" onclick="GetQRCode()">Create QR Code</button>
<div id="demo"></div>
<script>
function GetQRCode() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var ourJSON = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = "<img src=\"data:image/png;base64, " + ourJSON.image + "\">";
}
};
input = document.getElementById('inputbox').value
xhttp.open("GET", "/api/GenerateQRCode?text=" + input, true);
xhttp.send();
}
</script>
</body>
</html>
- This is an HTML document that serves as the front end for the QR Code generator.
- It contains an input field for entering text, a button to trigger QR Code generation, and a div to display the generated QR Code image.
- The GetQRCode() JavaScript function sends an HTTP request to the GenerateQRCode Azure Function with the text input as a query parameter.
- Upon receiving the response, it updates the demo div with the generated QR Code image.
- Styling is applied for a better visual experience.
6. Directory Visual
- The directory may look something like this:
7. CSProj File Visual
- The project file may look something like this:
8. Publish to Azure
- Right-click your project and select "Publish." Create a new instance or use an existing one. It's possible to pre-make the resource group and storage account or let the wizard create them.
- Once published, navigate to the generated domain and append '/api/form' to the URL. This will load the QR Code Generator form, input text, click the button, and witness the QR Code Generator Azure Function work its magic.
---
In following along with this tutorial, individuals acquire the expertise to configure a QR Code Serverless Function for Barcode Generation in Azure utilizing IDAutomation .NET Generator. This approach merely scratches the surface of the possibilities for integrating barcodes into a company's workflow.