How to Read & Write Barcode on AWS Lambda

This article was translated from English: Does it need improvement?
Translated
View the article in English
AWS Lambda

This how-to article provides a comprehensive guide to setting up an AWS Lambda function using IronBarcode. In this guide, you will learn how to configure IronBarcode to read from and write barcodes to an S3 bucket.

Installation

This article will use an S3 bucket, so the AWSSDK.S3 package is required.

Using IronBarcode Zip

If you are using IronBarcode ZIP, it is essential to set the temporary folder.

var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
$vbLabelText   $csharpLabel

The Microsoft.ML.OnnxRuntime package is required for reading barcodes. While writing barcodes works fine without it, the default mode for reading relies on machine learning (ML). If you switch to a reading mode that doesn't use ML, the package is not needed.

Create an AWS Lambda Project

With Visual Studio, creating a containerized AWS Lambda is an easy process:

  • Install the AWS Toolkit for Visual Studio
  • Select an 'AWS Lambda Project (.NET Core - C#)'
  • Select a '.NET 8 (Container Image)' blueprint, then select 'Finish'.

Select container image

Add Package Dependencies

The IronBarcode library in .NET 8 works on AWS Lambda without needing extra dependencies. To set it up, update the project's Dockerfile as follows:

FROM public.ecr.aws/lambda/dotnet:8

# Install necessary packages
RUN dnf update -y

WORKDIR /var/task

# This COPY command copies the .NET Lambda project's build artifacts from the host machine into the image. 
# The source of the COPY should match where the .NET Lambda project publishes its build artifacts. If the Lambda function is being built 
# with the AWS .NET Lambda Tooling, the `--docker-host-build-output-dir` switch controls where the .NET Lambda project
# will be built. The .NET Lambda project templates default to having `--docker-host-build-output-dir`
# set in the aws-lambda-tools-defaults.json file to "bin/Release/lambda-publish".
#
# Alternatively Docker multi-stage build could be used to build the .NET Lambda project inside the image.
# For more information on this approach check out the project's README.md file.
COPY "bin/Release/lambda-publish"  .

Modify the FunctionHandler Code

This example generates an EAN8 barcode, uploads it to an S3 bucket, and reads the newly created barcode. When using IronBarcode ZIP, configuring the temp folder is crucial because the library needs write permissions to copy the runtime folder from the DLLs.

using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronBarCode;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace IronBarcodeZipAwsLambda;

public class Function
{
    private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

    /// <summary>
    /// AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
    /// </summary>
    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    public async Task FunctionHandler(ILambdaContext context)
    {
        var awsTmpPath = @"/tmp/";
        IronBarCode.Installation.DeploymentPath = awsTmpPath;

        // Set your IronBarcode license key here
        IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";

        string filename = Guid.NewGuid().ToString();
        string bucketName = "deploymenttestbucket";
        string objectKey = $"IronBarcodeZip/{filename}.png";

        try
        {
            // Creating a barcode with EAN8 encoding
            var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);

            context.Logger.LogLine($"Barcode created.");

            // Upload the PNG image of the barcode to the specified S3 bucket
            await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());
            context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}");

            // Read and log the barcode value from the PNG binary data
            var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());
            foreach (var item in resultFromByte)
            {
                context.Logger.LogLine($"Barcode value is = {item.Value}");
            }
        }
        catch (Exception e)
        {
            context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
        }
    }

    /// <summary>
    /// Uploads a PNG byte array to the specified S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name of the S3 bucket.</param>
    /// <param name="objectKey">The object key for the uploaded file in the bucket.</param>
    /// <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
    private async Task UploadPngToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
    {
        using (var memoryStream = new MemoryStream(pdfBytes))
        {
            var request = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = objectKey,
                InputStream = memoryStream,
                ContentType = "image/png",
            };

            await _s3Client.PutObjectAsync(request);
        }
    }
}
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronBarCode;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace IronBarcodeZipAwsLambda;

public class Function
{
    private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

    /// <summary>
    /// AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
    /// </summary>
    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    public async Task FunctionHandler(ILambdaContext context)
    {
        var awsTmpPath = @"/tmp/";
        IronBarCode.Installation.DeploymentPath = awsTmpPath;

        // Set your IronBarcode license key here
        IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";

        string filename = Guid.NewGuid().ToString();
        string bucketName = "deploymenttestbucket";
        string objectKey = $"IronBarcodeZip/{filename}.png";

        try
        {
            // Creating a barcode with EAN8 encoding
            var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);

            context.Logger.LogLine($"Barcode created.");

            // Upload the PNG image of the barcode to the specified S3 bucket
            await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());
            context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}");

            // Read and log the barcode value from the PNG binary data
            var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());
            foreach (var item in resultFromByte)
            {
                context.Logger.LogLine($"Barcode value is = {item.Value}");
            }
        }
        catch (Exception e)
        {
            context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
        }
    }

    /// <summary>
    /// Uploads a PNG byte array to the specified S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name of the S3 bucket.</param>
    /// <param name="objectKey">The object key for the uploaded file in the bucket.</param>
    /// <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
    private async Task UploadPngToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
    {
        using (var memoryStream = new MemoryStream(pdfBytes))
        {
            var request = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = objectKey,
                InputStream = memoryStream,
                ContentType = "image/png",
            };

            await _s3Client.PutObjectAsync(request);
        }
    }
}
Imports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronBarCode

' Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
<Assembly: LambdaSerializer(GetType(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))>

Namespace IronBarcodeZipAwsLambda

	Public Class [Function]
		Private Shared ReadOnly _s3Client As IAmazonS3 = New AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1)

		''' <summary>
		''' AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
		''' </summary>
		''' <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
		Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
			Dim awsTmpPath = "/tmp/"
			IronBarCode.Installation.DeploymentPath = awsTmpPath

			' Set your IronBarcode license key here
			IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"

			Dim filename As String = Guid.NewGuid().ToString()
			Dim bucketName As String = "deploymenttestbucket"
			Dim objectKey As String = $"IronBarcodeZip/{filename}.png"

			Try
				' Creating a barcode with EAN8 encoding
				Dim myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8)

				context.Logger.LogLine($"Barcode created.")

				' Upload the PNG image of the barcode to the specified S3 bucket
				Await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData())
				context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}")

				' Read and log the barcode value from the PNG binary data
				Dim resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData())
				For Each item In resultFromByte
					context.Logger.LogLine($"Barcode value is = {item.Value}")
				Next item
			Catch e As Exception
				context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
			End Try
		End Function

		''' <summary>
		''' Uploads a PNG byte array to the specified S3 bucket.
		''' </summary>
		''' <param name="bucketName">The name of the S3 bucket.</param>
		''' <param name="objectKey">The object key for the uploaded file in the bucket.</param>
		''' <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
		Private Async Function UploadPngToS3Async(ByVal bucketName As String, ByVal objectKey As String, ByVal pdfBytes() As Byte) As Task
			Using memoryStream As New MemoryStream(pdfBytes)
				Dim request = New PutObjectRequest With {
					.BucketName = bucketName,
					.Key = objectKey,
					.InputStream = memoryStream,
					.ContentType = "image/png"
				}

				Await _s3Client.PutObjectAsync(request)
			End Using
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

Before the try block, the file destination is set to the IronBarcodeZip directory, with the name generated as a globally unique identifier (GUID). The CreateBarcode method is used to generate the barcode. Afterward, the PNG byte array is passed to the Read method to read the barcode. This demonstrates that the AWS Lambda function is capable of reading barcodes.

The Read method also accepts a BarcodeReaderOptions object, which you can customize to enable features such as reading multiple barcodes, targeting specific areas, using asynchronous and multithreaded processing, applying image correction filters, and much more.

Increase Memory and Timeout

The amount of memory allocated in the Lambda function will vary based on the size of the documents being processed and the number of documents processed simultaneously. As a baseline, set the memory to 512 MB and the timeout to 300 seconds in aws-lambda-tools-defaults.json.

{
    "function-memory-size": 512,
    "function-timeout": 300
}

When the memory is insufficient, the program will throw the error: 'Runtime exited with error: signal: killed.' Increasing the memory size can resolve this issue. For more details, refer to the troubleshooting article: AWS Lambda - Runtime Exited Signal: Killed.

Publish

To publish in Visual Studio, right-click on the project and select 'Publish to AWS Lambda...', then configure the necessary settings. You can read more about publishing a Lambda on the AWS website.

Try It Out!

You can activate the Lambda function either through the Lambda console or through Visual Studio.

Preguntas Frecuentes

¿Cómo configuro la lectura y escritura de código de barras en AWS Lambda?

Para configurar la lectura y escritura de código de barras en AWS Lambda, utiliza la biblioteca IronBarcode descargándola y creando un proyecto AWS Lambda con Visual Studio. Modifica el código FunctionHandler para manejar operaciones de código de barras, configura las configuraciones del proyecto y despliega. Asegúrate de incluir dependencias de paquetes necesarias como AWSSDK.S3.

¿Qué paquetes son necesarios para el procesamiento de código de barras en AWS Lambda?

Para el procesamiento de código de barras en AWS Lambda, incluye el paquete AWSSDK.S3 para interacciones con S3 y opcionalmente el paquete Microsoft.ML.OnnxRuntime para lectura avanzada de código de barras con aprendizaje automático, lo cual puede no ser necesario si usas métodos estándar de lectura de códigos de barras.

¿Cómo puedo modificar el código FunctionHandler en AWS Lambda para tareas de códigos de barras?

Modifica el código FunctionHandler para crear y leer códigos de barras usando IronBarcode. Asegúrate de configurar la clave de licencia de IronBarcode y configurar la carpeta temporal para el correcto funcionamiento de los archivos ZIP de IronBarcode.

¿Cómo aumento la memoria y el tiempo de espera para una función de AWS Lambda que maneja códigos de barras?

Ajusta la configuración de memoria y tiempo de espera en el archivo aws-lambda-tools-defaults.json estableciendo el tamaño de memoria de la función en 512 MB y el tiempo de espera de la función en 300 segundos para satisfacer las necesidades de procesamiento de códigos de barras con IronBarcode.

¿Cómo publico una función Lambda usando Visual Studio para el procesamiento de códigos de barras?

Publica la función Lambda haciendo clic derecho en el proyecto en Visual Studio, seleccionando 'Publicar en AWS Lambda...' y configurando las opciones. Sigue la documentación de AWS para pasos detallados, asegurándote de que IronBarcode esté configurado correctamente.

¿Cómo puedo probar la función AWS Lambda desplegada para operaciones de códigos de barras?

Prueba la función Lambda activándola a través de la consola de AWS Lambda o directamente desde Visual Studio, asegurándote de que IronBarcode funcione correctamente y las tareas de procesamiento de códigos de barras se realicen según lo esperado.

¿Cuál es el papel del Dockerfile en la configuración del procesamiento de códigos de barras en AWS Lambda?

El Dockerfile ayuda a actualizar los paquetes necesarios y a copiar los artefactos de construcción del proyecto .NET Lambda en la imagen, facilitando el procesamiento sin problemas de códigos de barras con IronBarcode en AWS Lambda.

¿Por qué es importante configurar la carpeta temporal al usar bibliotecas de códigos de barras en AWS Lambda?

Configurar la carpeta temporal es esencial porque IronBarcode requiere permisos de escritura para la operación ZIP, asegurando que las carpetas en runtime se copien correctamente desde los DLLs para un funcionamiento sin problemas en AWS Lambda.

¿Puedo personalizar la lectura de códigos de barras en AWS Lambda?

Sí, IronBarcode permite la personalización de la lectura de códigos de barras usando BarcodeReaderOptions, lo cual incluye leer múltiples códigos de barras, apuntar a áreas específicas, habilitar el procesamiento asincrónico y aplicar filtros de corrección de imagen.

¿Qué debo hacer si encuentro el error 'Runtime exited with error: signal: killed' durante el procesamiento de códigos de barras?

Este error sugiere una asignación insuficiente de memoria. Aumenta la memoria de la función Lambda en el archivo aws-lambda-tools-defaults.json para resolver el problema mientras usas IronBarcode.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 1,935,276 | Versión: 2025.11 recién lanzado