AWS LambdaでQRコードを読み書きする方法

チャクニット・ビン
チャクニット・ビン
2024年10月10日
更新済み 2024年10月10日
共有:
This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to AWS LambdaでQRコードを読み書きする方法

このハウツー記事では、IronQRでAWS Lambda関数をセットアップするための詳細なガイドを提供します。 このチュートリアルでは、QRコードをS3バケットに直接読み書きするためのIronQRの設定方法を説明します。

インストール

この記事では S3 バケットを使用するため、AWSSDK.S3 パッケージが必要です。

今日から無料トライアルでIronQRをあなたのプロジェクトで使い始めましょう。

最初のステップ:
green arrow pointer

AWS Lambdaプロジェクトを作成する

Visual Studioを使用すれば、コンテナ化されたAWS Lambdaの作成は簡単なプロセスです。

  • AWS Toolkit for Visual Studioをインストールしてください
  • 'AWS Lambda Project (.NET Core - C#)'を選択します
  • 「.NET 8 (コンテナイメージ)」のブループリントを選択し、「終了」を選択します。

    コンテナイメージを選択

パッケージ依存関係を追加する

.NET 8のIronQRライブラリは、追加の依存関係を必要とせずにAWS Lambda上で動作します。 設定するには、プロジェクトのDockerfileを以下のように変更してください:


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

# 必要なパッケージをインストールする

RUN dnf update -y

作業ディレクトリ /var/task

# このCOPYコマンドは、ホストマシンからイメージ内に.NET Lambdaプロジェクトのビルドアーティファクトをコピーします。

# COPYのソースは、.NET Lambdaプロジェクトがビルドアーティファクトを公開する場所と一致する必要があります。

Lambda関数が構築されている場合

# AWS .NET Lambda ツーリングでは、`--docker-host-build-output-dir` スイッチで .NET Lambda プロジェクトの出力先を制御します。

# 構築されます。

.NET Lambda プロジェクト テンプレートはデフォルトで `--docker-host-build-output-dir` を持っています。

# aws-lambda-tools-defaults.json ファイルで "bin/Release/lambda-publish" に設定します。

もちろんです。テキストを提供してください。

# また、Dockerのマルチステージビルドを使用して、イメージ内で.NET Lambdaプロジェクトをビルドすることもできます。

# この手法についての詳細は、プロジェクトのREADME.mdファイルを確認してください。

COPY "bin/Release/lambda-publish"  .

関数ハンドラーコードの修正

この例では、QRコードを作成し、S3バケットにアップロードし、新しく生成されたQRコードを読み取ります。

tryブロックの前に、ファイルパスはIronQrNugetディレクトリ内で指定され、ファイル名としてグローバル一意識別子(GUID)が使用されています。 Write メソッドは、提供された値に基づいてQRコードを生成し、生成されたJPGバイト配列は Read メソッドに渡され、QRコードを読み取ります。 これは、このAWS Lambda関数が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);

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

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

        try
        {
            // Creating a qr is as simple as:
            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}");

            // Load the asset into QrImageInput
            QrImageInput imageInput = new QrImageInput(myQr.Save());

            // Create a QR Reader object
            QrReader reader = new QrReader();

            var resultFromByte = reader.Read(imageInput);

            foreach (var item in resultFromByte)
            {
                // Log the read value out
                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[] pdfBytes)
    {
        using (var memoryStream = new MemoryStream(pdfBytes))
        {
            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);

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

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

        try
        {
            // Creating a qr is as simple as:
            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}");

            // Load the asset into QrImageInput
            QrImageInput imageInput = new QrImageInput(myQr.Save());

            // Create a QR Reader object
            QrReader reader = new QrReader();

            var resultFromByte = reader.Read(imageInput);

            foreach (var item in resultFromByte)
            {
                // Log the read value out
                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[] pdfBytes)
    {
        using (var memoryStream = new MemoryStream(pdfBytes))
        {
            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)

		''' <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
			IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01"

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

			Try
				' Creating a qr is as simple as:
				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}")

				' Load the asset into QrImageInput
				Dim imageInput As New QrImageInput(myQr.Save())

				' Create a QR Reader object
				Dim reader As New QrReader()

				Dim resultFromByte = reader.Read(imageInput)

				For Each item In resultFromByte
					' Log the read value out
					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 pdfBytes() As Byte) As Task
			Using memoryStream As New MemoryStream(pdfBytes)
				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

メモリとタイムアウトの増加

Lambda関数のメモリ割り当ては、ドキュメントのサイズと同時に処理される数に依存します。 出発点として、メモリを512 MB、タイムアウトを300秒にaws-lambda-tools-defaults.jsonで設定します。


「function-memory-size」:512

「function-timeout」: 300

メモリが不足すると、プログラムは「Runtime exited with error: signal: killed」というエラーを発生します。メモリサイズを増やすことで、この問題を解決することができます。 詳細なガイダンスについては、トラブルシューティングの記事をご確認ください: AWS Lambda - ランタイムがシグナルで終了: Killed

出版

Visual Studioで公開するには、プロジェクトを右クリックし、'Publish to AWS Lambda...'を選択するだけです。その後、必要な設定を行います。 詳細については、AWSのウェブサイトをご覧ください。

お試しください!

Lambda 関数は、Lambda コンソールまたは Visual Studio を通じてアクティブ化できます。

チャクニット・ビン
ソフトウェアエンジニア
ChaknithはIronXLとIronBarcodeで作業しています。彼はC#と.NETに深い専門知識を持ち、ソフトウェアの改善と顧客サポートを支援しています。ユーザーとの対話から得た彼の洞察は、より良い製品、文書、および全体的な体験に貢献しています。