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

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を簡単に作成できます:

コンテナイメージを選択

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

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

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

FunctionHandlerコードの修正

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

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

        /// <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

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

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

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

メモリが不足している場合、プログラムは"ランタイムがエラーで終了しました: シグナル: 強制終了"というエラーを発生させます。メモリ サイズを増やすと、この問題を解決できる場合があります。 詳細なガイダンスについては、トラブルシューティングの記事" AWS Lambda - ランタイム終了シグナル: 強制終了"を参照してください。

公開

Visual Studio で公開するには、プロジェクトを右クリックし、"AWS Lambda に公開..."を選択し、必要な設定を構成します。 詳細については、 AWS Web サイトをご覧ください。

試してみましょう!

LambdaコンソールまたはVisual Studioを使用して、Lambda関数をアクティブにすることができます。

よくある質問

AWS Lambda 上の C# プロジェクトに QR コードライブラリを統合するにはどうすればよいですか?

QRコードライブラリ(IronQRなど)をAWS LambdaのC#プロジェクトに統合するには、IronQRライブラリをダウンロードし、Visual Studioを使用してコンテナ化されたAWS Lambdaプロジェクトを作成し、QRコード操作をサポートするように環境を設定します。

AWS Lambda 用の IronQR を設定する手順は何ですか?

Visual Studio でコンテナ化されたプロジェクトテンプレートを設定し、Dockerfile を修正し、FunctionHandler を更新し、スムーズな操作を確保するためにメモリとタイムアウト設定を調整することで、AWS Lambda 用の IronQR を設定します。

C# ライブラリを使用して AWS S3 で QR コードを管理するにはどうすればよいですか?

IronQR を使用すると、QR コードを作成し、AWS S3 バケットにアップロードして、そこから読み取ることができます。これは、IronQR ライブラリを利用して、AWSSDK.S3 パッケージと組み合わせて S3 バケットとの操作を処理します。

IronQR を使用している AWS Lambda 関数のパフォーマンスが良くない場合はどうすればいいですか?

AWS Lambda 関数がパフォーマンスが良くない場合、aws-lambda-tools-defaults.json ファイルでメモリとタイムアウト設定を増やし、関数により多くのリソースを割り当てることを検討してください。

C# Lambda 関数を AWS に展開するにはどうすればよいですか?

Visual Studio の「'Publish to AWS Lambda...'」オプションを使用し、必要な設定を行い、AWS Toolkit を利用して展開します。

Visual Studio で AWS Lambda 関数をテストすることは可能ですか?

はい、AWS Toolkitを使用して関数を呼び出し、開発環境内で直接出力を確認することで、Visual StudioでAWS Lambda関数をテストできます。

AWS Lambda 関数のメモリの問題をトラブルシューティングするにはどうすればよいですか?

メモリの問題をトラブルシューティングするには、aws-lambda-tools-defaults.json ファイルで関数のメモリ割り当てを増やし、再展開後に関数のパフォーマンスを監視します。

AWS Lambda プロジェクトで Dockerfile を修正することの重要性は何ですか?

AWS Lambda プロジェクトで Dockerfile を修正することは、環境を正しく設定するために重要であり、リポジトリの更新や必要なビルド成果物を関数が正しく実行するためにコピーすることを含みます。

AWS Lambda 関数が QR コード操作を効率よく処理するようにするにはどうすればよいですか?

AWS Lambda 関数が QR コード操作を効率よく処理するようにするには、メモリとタイムアウト設定を最適化し、IronQR のような適切なライブラリを使用し、Dockerfile とプロジェクト設定を正しく構成します。

AWS Lambda で QR コードの生成と取得を自動化できますか?

はい、IronQR を使用して AWS Lambda で QR コードの生成と取得を自動化できます。このライブラリを用いると、QR コードをプログラムで作成し、S3 にアップロードし、必要に応じて読み取ることができます。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

準備はできましたか?
Nuget ダウンロード 58,270 | バージョン: 2026.2 リリース