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.
Cómo leer y escribir códigos QR en AWS Lambda
- Descarga una biblioteca de C# para leer y escribir códigos QR
- Crear la plantilla de proyecto contenedor para AWS Lambda
- Modificar el código del Dockerfile y FunctionHandler
- Aumentar la configuración de memoria y tiempo de espera
- Desplegar e invocar la función para ver los resultados en S3
Instalación
Este artículo utilizará un bucket S3, por lo que se requiere el paquete AWSSDK.S3.
Empiece a usar IronQR en su proyecto hoy con una prueba gratuita.
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'.

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);
}
}
}
}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 NamespaceImports 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 NamespaceAumentar 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, establezca 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, consulte el artículo de resolución de problemas: AWS Lambda - Signal de salida del tiempo de ejecución: 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, visite el sitio web de AWS.
¡Pruébalo!
Puede activar la función Lambda a través de la consola Lambda o a través de Visual Studio.
Preguntas frecuentes
¿Cómo configuro IronQR en AWS Lambda?
Para configurar IronQR en AWS Lambda, necesita crear un proyecto en contenedor en Visual Studio, añadir la biblioteca IronQR, configurar las dependencias, modificar el Dockerfile y desplegar la función con la memoria y configuración de tiempo adecuadas.
¿Cuáles son los requisitos previos para usar IronQR en AWS Lambda?
Necesita Visual Studio, AWS Toolkit para Visual Studio, el paquete AWSSDK.S3 para la interacción con el bucket S3 y la biblioteca IronQR.
¿Puede IronQR leer y escribir códigos QR directamente en un bucket S3?
Sí, IronQR se puede configurar para leer y escribir códigos QR directamente en un bucket S3 en AWS Lambda.
¿Cómo aumento la memoria y los ajustes de tiempo de espera para IronQR en AWS Lambda?
Puede aumentar la memoria y los ajustes de tiempo de espera ajustando los campos 'function-memory-size' y 'function-timeout' en el archivo aws-lambda-tools-defaults.json.
¿Cómo se integra la biblioteca IronQR en un proyecto en contenedor .NET 8?
IronQR se integra añadiendo la biblioteca al proyecto, modificando el Dockerfile y configurando el FunctionHandler para crear y leer códigos QR usando IronQR.
¿Qué debo hacer si la función Lambda se queda sin memoria?
Si la función se queda sin memoria, intente aumentar la configuración de asignación de memoria en el archivo aws-lambda-tools-defaults.json y asegúrese de que tenga suficientes recursos para operar eficientemente.
¿Cómo despliego una función AWS Lambda con IronQR?
Despliega la función configurando el proyecto para AWS Lambda, aumentando los ajustes de memoria y tiempo de espera si es necesario, y usando Visual Studio para publicar el proyecto en AWS Lambda.
¿Se requiere configuración adicional para que IronQR funcione en AWS Lambda?
No se requieren dependencias adicionales para que IronQR funcione en AWS Lambda al usar .NET 8, aparte de la configuración estándar de AWS.
¿Qué se requiere para publicar un proyecto con IronQR en AWS Lambda en Visual Studio?
Para publicar, haz clic derecho en el proyecto, selecciona 'Publicar en AWS Lambda...' y configura los ajustes necesarios en el diálogo de publicación.
¿Cómo puedo probar la función Lambda desplegada usando IronQR?
Puede activar y probar la función Lambda a través de la consola de AWS Lambda o directamente desde Visual Studio después de la implementación.
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 estructurados y visualmente atractivos.