How to Read & Write QR Codes on AWS Lambda

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to How to Read & Write QR Codes on AWS Lambda

Cet article pratique propose un guide détaillé pour la configuration d'une fonction AWS Lambda avec IronQR. Dans ce tutoriel, vous découvrirez comment configurer IronQR pour lire et écrire des codes QR directement dans un bucket S3.

Installation

Cet article utilisera un bucket S3, le package AWSSDK.S3 est donc nécessaire.

Commencez à utiliser IronQR dans votre projet aujourd'hui avec un essai gratuit.

Première étape :
green arrow pointer

Créer un projet AWS Lambda

Avec Visual Studio, la création d'un AWS Lambda conteneurisé est un processus facile :

  • Installez le AWS Tookit pour Visual Studio
  • Sélectionnez un 'Projet AWS Lambda (.NET Core - C#)'
  • Sélectionnez un modèle '.NET 8 (Container Image)', puis cliquez sur 'Finish'.

Sélectionner l'image du conteneur

Ajouter des dépendances de paquets

La bibliothèque IronQR for .NET 8 fonctionne sur AWS Lambda sans nécessiter de dépendances supplémentaires. Pour le configurer, modifiez le fichier Docker du projet comme indiqué ci-dessous :

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"  .

Modifier le code de FunctionHandler

Cet exemple crée un code QR, le télécharge dans un bac S3 et lit le code QR nouvellement généré.

Le chemin d'accès au fichier est spécifié dans le répertoire IronQrNuget, avec un identifiant unique global (GUID) utilisé comme nom de fichier. La méthode Write génère le code QR sur la base de la valeur fournie, et le tableau d'octets JPG qui en résulte est ensuite transmis à la méthode Read pour la lecture du code QR. Ceci démontre que cette fonction AWS Lambda est capable de lire les codes 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

Augmenter la mémoire et le délai d'attente

L'allocation de mémoire pour la fonction Lambda dépend de la taille des documents et du nombre de documents traités simultanément. Pour commencer, définissez la mémoire à 512 Mo et le délai d'attente à 300 secondes dans le fichier aws-lambda-tools-defaults.json.

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

Si la mémoire est insuffisante, le programme affichera l'erreur suivante : "Runtime exited with error : signal : killed" L'augmentation de la taille de la mémoire peut aider à résoudre ce problème. Pour plus d'informations, consultez l'article sur le dépannage : AWS Lambda - Runtime Exited Signal : Killed.

Publier

Pour publier dans Visual Studio, il suffit de cliquer avec le bouton droit de la souris sur le projet et de choisir "Publier sur AWS Lambda.. Configurez ensuite les paramètres requis. Pour plus d'informations, visitez le site web de l'AWS.

Essayer!

Vous pouvez activer la fonction Lambda via la console Lambda ou via Visual Studio.

Questions Fréquemment Posées

Comment puis-je intégrer une bibliothèque de codes QR dans mon projet C# sur AWS Lambda ?

Vous pouvez intégrer une bibliothèque de codes QR comme IronQR dans votre projet C# sur AWS Lambda en téléchargeant la bibliothèque IronQR, en créant un projet AWS Lambda conteneurisé en utilisant Visual Studio et en configurant votre environnement pour prendre en charge les opérations de code QR.

Quelles sont les étapes pour configurer IronQR pour AWS Lambda ?

Configurez IronQR pour AWS Lambda en mettant en place un modèle de projet conteneurisé dans Visual Studio, en modifiant le Dockerfile, en mettant à jour le FunctionHandler et en ajustant les paramètres de mémoire et de temporisation pour assurer un bon fonctionnement.

Comment gérer les codes QR avec AWS S3 en utilisant une bibliothèque C# ?

Avec IronQR, vous pouvez gérer les codes QR en les créant, les téléchargeant et les lisant à partir de compartiments Amazon S3. Cela implique d'utiliser la bibliothèque IronQR en combinaison avec le package AWSSDK.S3 pour gérer les opérations avec les compartiments S3.

Que dois-je faire si ma fonction AWS Lambda utilisant IronQR ne fonctionne pas bien ?

Si votre fonction AWS Lambda ne fonctionne pas bien, envisagez d'augmenter les paramètres de mémoire et de temporisation dans votre fichier aws-lambda-tools-defaults.json pour allouer plus de ressources à la fonction.

Comment puis-je déployer une fonction Lambda C# sur AWS ?

Déployez une fonction Lambda C# sur AWS en utilisant l'option 'Publier vers AWS Lambda...' de Visual Studio, en configurant les paramètres nécessaires et en utilisant AWS Toolkit pour le déploiement.

Est-il possible de tester ma fonction AWS Lambda dans Visual Studio ?

Oui, vous pouvez tester votre fonction AWS Lambda dans Visual Studio en utilisant AWS Toolkit pour invoquer la fonction et vérifier directement la sortie dans votre environnement de développement.

Comment puis-je résoudre les problèmes de mémoire avec ma fonction AWS Lambda ?

Pour résoudre les problèmes de mémoire, augmentez l'allocation de mémoire dans le fichier aws-lambda-tools-defaults.json et surveillez les performances de la fonction après le redéploiement.

Quelle est l'importance de modifier le Dockerfile dans un projet AWS Lambda ?

La modification du Dockerfile dans un projet AWS Lambda est cruciale pour configurer correctement l'environnement, y compris la mise à jour des référentiels et la copie des artefacts de construction nécessaires pour que la fonction s'exécute correctement.

Comment puis-je m'assurer que ma fonction AWS Lambda gère efficacement les opérations de code QR ?

Assurez-vous que votre fonction AWS Lambda gère efficacement les opérations de code QR en optimisant les paramètres de mémoire et de temporisation, en utilisant les bibliothèques appropriées comme IronQR et en configurant correctement le Dockerfile et les paramètres du projet.

Puis-je automatiser la génération et la récupération des codes QR dans AWS Lambda ?

Oui, vous pouvez automatiser la génération et la récupération des codes QR dans AWS Lambda en utilisant IronQR. La bibliothèque vous permet de créer des codes QR par programmation, de les télécharger vers S3 et de les lire au besoin.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 47,669 | Version : 2025.11 vient de sortir