Cómo leer y escribir códigos QR en AWS Lambda

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to Cómo leer y escribir códigos QR en AWS Lambda

Este artículo ofrece una guía detallada para configurar una función de AWS Lambda con IronQR. En este tutorial, descubrirás cómo configurar IronQR para leer y escribir códigos QR directamente en un bucket de S3.

Instalación

Este artículo utilizará un bucket S3, por lo que se requiere el paquete AWSSDK.S3.

Comience a usar IronQR en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer

Crear un proyecto de AWS Lambda

Con Visual Studio, crear un AWS Lambda en contenedor es un proceso sencillo:

  • Instalar el AWS Toolkit for Visual Studio
  • Seleccionar un 'Proyecto AWS Lambda (.NET Core - C#)'
  • Seleccionar un modelo '.NET 8 (Imagen de Contenedor)', luego seleccionar 'Finalizar'.

Seleccionar imagen de contenedor

Agregar dependencias de paquetes

La biblioteca IronQR en .NET 8 funciona en AWS Lambda sin requerir dependencias adicionales. Para configurarlo, modifica el Dockerfile del proyecto como se muestra a continuación:

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

# Install necessary packages and update repositories
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"  .

Modificar el código del FunctionHandler

Este ejemplo crea un código QR, lo carga en un bucket de S3 y lee el código QR recién generado.

La ruta del archivo se especifica en el directorio IronQrNuget, con un identificador único global (GUID) usado como nombre de archivo. El método Write genera el código QR basado en el valor proporcionado, y la matriz de bytes JPG resultante se pasa al método Read para leer el código QR. Esto demuestra que esta función de AWS Lambda es capaz de leer códigos QR.

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

// 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 IronQrNuGetAwsLambda
{
    public class Function
    {
        private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

        /// <summary>
        /// Main handler for AWS Lambda
        /// </summary>
        /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
        /// <returns></returns>
        public async Task FunctionHandler(ILambdaContext context)
        {
            // Set the license key for IronQR
            IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01";

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

            try
            {
                // Create a QR code with the content "12345"
                var myQr = QrWriter.Write("12345");

                context.Logger.LogLine("QR created.");

                // Upload the JPG to S3
                await UploadJpgToS3Async(bucketName, objectKey, myQr.Save().ExportBytesAsJpg());

                context.Logger.LogLine($"QR uploaded successfully to {bucketName}/{objectKey}");

                // Read the QR code
                QrImageInput imageInput = new QrImageInput(myQr.Save());
                QrReader reader = new QrReader();
                var resultFromByte = reader.Read(imageInput);

                foreach (var item in resultFromByte)
                {
                    // Log the read value
                    context.Logger.LogLine($"QR value is = {item.Value}");
                }
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
            }
        }

        // Function to upload the JPG file to S3
        private async Task UploadJpgToS3Async(string bucketName, string objectKey, byte[] jpgBytes)
        {
            using (var memoryStream = new MemoryStream(jpgBytes))
            {
                var request = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = objectKey,
                    InputStream = memoryStream,
                    ContentType = "image/jpg",
                };

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

// 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 IronQrNuGetAwsLambda
{
    public class Function
    {
        private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

        /// <summary>
        /// Main handler for AWS Lambda
        /// </summary>
        /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
        /// <returns></returns>
        public async Task FunctionHandler(ILambdaContext context)
        {
            // Set the license key for IronQR
            IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01";

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

            try
            {
                // Create a QR code with the content "12345"
                var myQr = QrWriter.Write("12345");

                context.Logger.LogLine("QR created.");

                // Upload the JPG to S3
                await UploadJpgToS3Async(bucketName, objectKey, myQr.Save().ExportBytesAsJpg());

                context.Logger.LogLine($"QR uploaded successfully to {bucketName}/{objectKey}");

                // Read the QR code
                QrImageInput imageInput = new QrImageInput(myQr.Save());
                QrReader reader = new QrReader();
                var resultFromByte = reader.Read(imageInput);

                foreach (var item in resultFromByte)
                {
                    // Log the read value
                    context.Logger.LogLine($"QR value is = {item.Value}");
                }
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
            }
        }

        // Function to upload the JPG file to S3
        private async Task UploadJpgToS3Async(string bucketName, string objectKey, byte[] jpgBytes)
        {
            using (var memoryStream = new MemoryStream(jpgBytes))
            {
                var request = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = objectKey,
                    InputStream = memoryStream,
                    ContentType = "image/jpg",
                };

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

' 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 IronQrNuGetAwsLambda
	Public Class [Function]
		Private Shared ReadOnly _s3Client As IAmazonS3 = New AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1)

		''' <summary>
		''' Main handler for AWS Lambda
		''' </summary>
		''' <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
		''' <returns></returns>
		Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
			' Set the license key for IronQR
			IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01"

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

			Try
				' Create a QR code with the content "12345"
				Dim myQr = QrWriter.Write("12345")

				context.Logger.LogLine("QR created.")

				' Upload the JPG to S3
				Await UploadJpgToS3Async(bucketName, objectKey, myQr.Save().ExportBytesAsJpg())

				context.Logger.LogLine($"QR uploaded successfully to {bucketName}/{objectKey}")

				' Read the QR code
				Dim imageInput As New QrImageInput(myQr.Save())
				Dim reader As New QrReader()
				Dim resultFromByte = reader.Read(imageInput)

				For Each item In resultFromByte
					' Log the read value
					context.Logger.LogLine($"QR value is = {item.Value}")
				Next item
			Catch e As Exception
				context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
			End Try
		End Function

		' Function to upload the JPG file to S3
		Private Async Function UploadJpgToS3Async(ByVal bucketName As String, ByVal objectKey As String, ByVal jpgBytes() As Byte) As Task
			Using memoryStream As New MemoryStream(jpgBytes)
				Dim request = New PutObjectRequest With {
					.BucketName = bucketName,
					.Key = objectKey,
					.InputStream = memoryStream,
					.ContentType = "image/jpg"
				}

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

Aumentar la memoria y el tiempo de espera

La asignación de memoria para la función Lambda depende del tamaño de los documentos y del número procesado simultáneamente. Como punto de partida, establece la memoria en 512 MB y el tiempo de espera en 300 segundos en el aws-lambda-tools-defaults.json.

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

Si la memoria es insuficiente, el programa generará el error: 'Runtime exited with error: signal: killed.' Aumentar el tamaño de la memoria puede ayudar a resolver este problema. Para obtener más orientación, consulta el artículo de solución de problemas: AWS Lambda - Runtime Exited Signal: Killed.

Publicar

Para publicar en Visual Studio, simplemente haz clic con el botón derecho en el proyecto y elige 'Publicar en AWS Lambda...' Luego, configura los ajustes necesarios. Para más información, visita el sitio web de AWS.

¡Pruébalo!

Puedes activar la función Lambda ya sea a través de la consola de Lambda o a través de Visual Studio.

Preguntas Frecuentes

¿Cómo puedo integrar una biblioteca de código QR en mi proyecto C# en AWS Lambda?

Puedes integrar una biblioteca de código QR como IronQR en tu proyecto C# en AWS Lambda descargando la biblioteca IronQR, creando un proyecto contenedor de AWS Lambda usando Visual Studio y configurando tu entorno para soportar operaciones de código QR.

¿Cuáles son los pasos para configurar IronQR para AWS Lambda?

Configura IronQR para AWS Lambda estableciendo una plantilla de proyecto contenedor en Visual Studio, modificando el Dockerfile, actualizando el FunctionHandler y ajustando la configuración de memoria y tiempo de espera para asegurar un funcionamiento fluido.

¿Cómo gestiono los códigos QR con AWS S3 usando una biblioteca C#?

Usando IronQR, puedes gestionar códigos QR creando, subiendo a y leyendo desde los buckets de AWS S3. Esto implica utilizar la biblioteca IronQR en combinación con el paquete AWSSDK.S3 para manejar operaciones con buckets S3.

¿Qué debería hacer si mi función AWS Lambda usando IronQR no está funcionando bien?

Si tu función AWS Lambda no está funcionando bien, considera aumentar la configuración de memoria y tiempo de espera en tu archivo aws-lambda-tools-defaults.json para asignar más recursos a la función.

¿Cómo puedo desplegar una función Lambda C# en AWS?

Despliega una función Lambda C# en AWS usando la opción 'Publicar en AWS Lambda...' de Visual Studio, configurando las configuraciones necesarias y utilizando AWS Toolkit para el despliegue.

¿Es posible probar mi función AWS Lambda en Visual Studio?

Sí, puedes probar tu función AWS Lambda en Visual Studio usando AWS Toolkit para invocar la función y verificar su salida directamente dentro de tu entorno de desarrollo.

¿Cómo puedo solucionar problemas de memoria con mi función AWS Lambda?

Para solucionar problemas de memoria, aumenta la asignación de memoria de la función en el archivo aws-lambda-tools-defaults.json y monitorea el rendimiento de la función después de volver a desplegar.

¿Cuál es la importancia de modificar el Dockerfile en un proyecto de AWS Lambda?

Modificar el Dockerfile en un proyecto de AWS Lambda es crucial para configurar el entorno correctamente, incluyendo la actualización de repositorios y la copia de artefactos de construcción necesarios para que la función se ejecute correctamente.

¿Cómo aseguro que mi función AWS Lambda maneje eficientemente las operaciones de código QR?

Asegura que tu función AWS Lambda maneje eficientemente las operaciones de código QR optimizando la configuración de memoria y tiempo de espera, utilizando bibliotecas adecuadas como IronQR y configurando correctamente el Dockerfile y la configuración del proyecto.

¿Puedo automatizar la generación y recuperación de códigos QR en AWS Lambda?

Sí, puedes automatizar la generación y recuperación de códigos QR en AWS Lambda usando IronQR. La biblioteca te permite crear códigos QR de manera programada, subirlos a S3 y leerlos como se necesite.

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 51,390 | Version: 2025.11 recién lanzado