AWS LambdaでQRコードを読み書きする方法
このハウツー記事では、IronQR を使用して AWS Lambda 関数を設定するための詳細なガイドを提供します。 このチュートリアルでは、QR コードを S3 バケットに直接読み書きするために IronQR を設定する方法について説明します。
AWS LambdaでQRコードを読み書きする方法
- QRコードを読み書きするためのC#ライブラリをダウンロード
- AWS Lambda のコンテナ化されたプロジェクトテンプレートを作成する
- Dockerfile と FunctionHandler コードを修正する
- メモリとタイムアウト設定を増やす
- 関数を展開して S3 に結果を確認する
インストール
この記事ではS3バケットを使用するため、AWSSDK.S3パッケージが必要です。
無料トライアルで今日からプロジェクトにIronQRを使用し始めましょう。
AWS Lambdaプロジェクトを作成
Visual Studioを使用すれば、コンテナ化されたAWS Lambdaを簡単に作成できます:
- AWS Toolkit for Visual Studioをインストールします
- 'AWS Lambda Project (.NET Core - C#)' を選択
- '.NET 8 (Container Image)' ブループリントを選択し、次に '完了' を選択

パッケージ依存関係を追加
.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バイト配列を 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);
/// <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 Namespaceメモリとタイムアウトの増加
Lambda 関数のメモリ割り当ては、ドキュメントのサイズと同時に処理される数によって異なります。 開始点として、aws-lambda-tools-defaults.jsonにメモリを512 MB、タイムアウトを300秒に設定します。
"function-memory-size" : 512,
"function-timeout" : 300
メモリが不足している場合、プログラムは"ランタイムがエラーで終了しました: シグナル: 強制終了"というエラーを発生させます。メモリ サイズを増やすと、この問題を解決できる場合があります。 さらなるガイダンスを得るには、トラブルシューティング記事を確認してください:AWS Lambda - Runtime Exited Signal: Killed。
公開
Visual Studio で公開するには、プロジェクトを右クリックし、"AWS Lambda に公開..."を選択し、必要な設定を構成します。 詳細については、AWSウェブサイトをご覧ください。
試してみましょう!
Lambda関数はLambdaコンソールまたはVisual Studioでアクティブ化できます。
よくある質問
AWS LambdaでIronQRをセットアップする方法は?
AWS LambdaでIronQRをセットアップするには、Visual Studioでコンテナ化されたプロジェクトを作成し、IronQRライブラリを追加し、依存関係を設定し、Dockerfileを修正して、適切なメモリとタイムアウト設定で関数をデプロイする必要があります。
AWS LambdaでIronQRを使用するために必要な前提条件は何ですか?
Visual Studio、AWS Toolkit for Visual Studio、S3バケットとのインタラクション用のAWSSDK.S3パッケージ、そしてIronQRライブラリが必要です。
IronQRはS3バケットに直接QRコードを読み書きできますか?
はい、IronQRはAWS Lambda上でS3バケットに直接QRコードを読み書きするように設定可能です。
AWS LambdaでIronQRのメモリとタイムアウト設定を増やす方法は?
メモリとタイムアウト設定は、aws-lambda-tools-defaults.jsonファイルで'function-memory-size'と'function-timeout'フィールドを調整することで増やすことができます。
.NET 8のコンテナ化されたプロジェクトにIronQRライブラリを統合する方法は?
IronQRはライブラリをプロジェクトに追加し、Dockerfileを修正し、IronQRを使用してQRコードを作成および読み取るためにFunctionHandlerを設定することで統合されます。
Lambda関数がメモリ不足になった場合はどうすればよいですか?
関数がメモリ不足になった場合、aws-lambda-tools-defaults.jsonファイルでメモリ割り当て設定を増やし、十分なリソースが効率的に動作するように確保してください。
IronQRを使用してAWS Lambda関数をデプロイする方法は?
プロジェクトをAWS Lambda用に設定し、必要に応じてメモリとタイムアウト設定を増やし、Visual Studioを使用してプロジェクトをAWS Lambdaに公開して関数をデプロイします。
IronQRがAWS Lambda上で動作するための追加のセットアップは必要ですか?
標準のAWS設定以外に、.NET 8を使用する場合、IronQRがAWS Lambdaで動作するために追加の依存関係は必要ありません。
Visual StudioでIronQRを使ってプロジェクトをAWS Lambdaに公開するには何が必要ですか?
公開するには、プロジェクトを右クリックし、『Publish to AWS Lambda...』を選択して、公開ダイアログで必要な設定を構成します。
IronQRを使用してデプロイされたLambda関数をテストするにはどうすればよいですか?
AWS LambdaコンソールまたはVisual Studioから直接デプロイ後にLambda関数を起動してテストすることができます。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。