AWS Lambdaでバーコードの読み書きをする方法
このハウツー記事は、IronBarcodeを使用してAWS Lambda関数をセットアップするための包括的なガイドを提供します。 このガイドでは、IronBarcodeを設定してS3バケットからバーコードを読み取ったり書き込んだりする方法を学びます。
AWS Lambdaでバーコードの読み書きをする方法
- バーコードを読み書きするC#ライブラリをダウンロード
- プロジェクトテンプレートを作成し、選択
- FunctionHandlerコードを修正
- プロジェクトを設定してデプロイ
- 関数を呼び出し、S3で結果を確認
インストール
この記事ではS3バケットを使用するため、AWSSDK.S3パッケージが必要です。
IronBarcode Zipの使用
IronBarcode ZIPを使用する場合、一時フォルダを設定することが重要です。
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPathDim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPathMicrosoft.ML.OnnxRuntimeパッケージはバーコードを読むために必要です。 バーコードの書き込みはそれなしでも正常に動作しますが、読み取りのデフォルトモードは機械学習(ML)に依存しています。 MLを使用しない読み取りモードに切り替える場合、そのパッケージは必要ありません。
AWS Lambdaプロジェクトを作成
Visual Studioを使用すれば、コンテナ化されたAWS Lambdaを簡単に作成できます:
- AWS Toolkit for Visual Studioをインストールします
- 'AWS Lambda Project (.NET Core - C#)' を選択
- '.NET 8 (Container Image)' ブループリントを選択し、次に '完了' を選択

パッケージ依存関係を追加
.NET 8のIronBarcodeライブラリは、追加の依存関係なしでAWS Lambdaで動作します。 これをセットアップするには、プロジェクトのDockerfileを次のように更新します:
FROM public.ecr.aws/lambda/dotnet:8
# Install necessary packages
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コードの修正
この例は、EAN8バーコードを生成し、それをS3バケットにアップロードし、新しく作成されたバーコードを読み取ります。 IronBarcode ZIPを使用する際、一時フォルダの設定は重要です。ライブラリは、DLLからランタイムフォルダをコピーするための書き込み権限が必要です。
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronBarCode;
// 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 IronBarcodeZipAwsLambda;
public class Function
{
private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);
/// <summary>
/// AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
/// </summary>
/// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
public async Task FunctionHandler(ILambdaContext context)
{
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
// Set your IronBarcode license key here
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
string filename = Guid.NewGuid().ToString();
string bucketName = "deploymenttestbucket";
string objectKey = $"IronBarcodeZip/{filename}.png";
try
{
// Creating a barcode with EAN8 encoding
var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);
context.Logger.LogLine($"Barcode created.");
// Upload the PNG image of the barcode to the specified S3 bucket
await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());
context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}");
// Read and log the barcode value from the PNG binary data
var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());
foreach (var item in resultFromByte)
{
context.Logger.LogLine($"Barcode value is = {item.Value}");
}
}
catch (Exception e)
{
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
}
}
/// <summary>
/// Uploads a PNG byte array to the specified S3 bucket.
/// </summary>
/// <param name="bucketName">The name of the S3 bucket.</param>
/// <param name="objectKey">The object key for the uploaded file in the bucket.</param>
/// <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
private async Task UploadPngToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
{
using (var memoryStream = new MemoryStream(pdfBytes))
{
var request = new PutObjectRequest
{
BucketName = bucketName,
Key = objectKey,
InputStream = memoryStream,
ContentType = "image/png",
};
await _s3Client.PutObjectAsync(request);
}
}
}using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronBarCode;
// 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 IronBarcodeZipAwsLambda;
public class Function
{
private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);
/// <summary>
/// AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
/// </summary>
/// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
public async Task FunctionHandler(ILambdaContext context)
{
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
// Set your IronBarcode license key here
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
string filename = Guid.NewGuid().ToString();
string bucketName = "deploymenttestbucket";
string objectKey = $"IronBarcodeZip/{filename}.png";
try
{
// Creating a barcode with EAN8 encoding
var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);
context.Logger.LogLine($"Barcode created.");
// Upload the PNG image of the barcode to the specified S3 bucket
await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());
context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}");
// Read and log the barcode value from the PNG binary data
var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());
foreach (var item in resultFromByte)
{
context.Logger.LogLine($"Barcode value is = {item.Value}");
}
}
catch (Exception e)
{
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
}
}
/// <summary>
/// Uploads a PNG byte array to the specified S3 bucket.
/// </summary>
/// <param name="bucketName">The name of the S3 bucket.</param>
/// <param name="objectKey">The object key for the uploaded file in the bucket.</param>
/// <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
private async Task UploadPngToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
{
using (var memoryStream = new MemoryStream(pdfBytes))
{
var request = new PutObjectRequest
{
BucketName = bucketName,
Key = objectKey,
InputStream = memoryStream,
ContentType = "image/png",
};
await _s3Client.PutObjectAsync(request);
}
}
}Imports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronBarCode
' 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 IronBarcodeZipAwsLambda
Public Class [Function]
Private Shared ReadOnly _s3Client As IAmazonS3 = New AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1)
''' <summary>
''' AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
''' </summary>
''' <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
' Set your IronBarcode license key here
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
Dim filename As String = Guid.NewGuid().ToString()
Dim bucketName As String = "deploymenttestbucket"
Dim objectKey As String = $"IronBarcodeZip/{filename}.png"
Try
' Creating a barcode with EAN8 encoding
Dim myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8)
context.Logger.LogLine($"Barcode created.")
' Upload the PNG image of the barcode to the specified S3 bucket
Await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData())
context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}")
' Read and log the barcode value from the PNG binary data
Dim resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData())
For Each item In resultFromByte
context.Logger.LogLine($"Barcode value is = {item.Value}")
Next item
Catch e As Exception
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
End Try
End Function
''' <summary>
''' Uploads a PNG byte array to the specified S3 bucket.
''' </summary>
''' <param name="bucketName">The name of the S3 bucket.</param>
''' <param name="objectKey">The object key for the uploaded file in the bucket.</param>
''' <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
Private Async Function UploadPngToS3Async(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/png"
}
Await _s3Client.PutObjectAsync(request)
End Using
End Function
End Class
End NamespaceImports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronBarCode
' 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 IronBarcodeZipAwsLambda
Public Class [Function]
Private Shared ReadOnly _s3Client As IAmazonS3 = New AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1)
''' <summary>
''' AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
''' </summary>
''' <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
' Set your IronBarcode license key here
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
Dim filename As String = Guid.NewGuid().ToString()
Dim bucketName As String = "deploymenttestbucket"
Dim objectKey As String = $"IronBarcodeZip/{filename}.png"
Try
' Creating a barcode with EAN8 encoding
Dim myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8)
context.Logger.LogLine($"Barcode created.")
' Upload the PNG image of the barcode to the specified S3 bucket
Await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData())
context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}")
' Read and log the barcode value from the PNG binary data
Dim resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData())
For Each item In resultFromByte
context.Logger.LogLine($"Barcode value is = {item.Value}")
Next item
Catch e As Exception
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
End Try
End Function
''' <summary>
''' Uploads a PNG byte array to the specified S3 bucket.
''' </summary>
''' <param name="bucketName">The name of the S3 bucket.</param>
''' <param name="objectKey">The object key for the uploaded file in the bucket.</param>
''' <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
Private Async Function UploadPngToS3Async(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/png"
}
Await _s3Client.PutObjectAsync(request)
End Using
End Function
End Class
End Namespacetryブロックの前に、ファイルの宛先は IronBarcodeZipディレクトリに設定され、名前はグローバルユニーク識別子(GUID)として生成されます。 CreateBarcodeメソッドはバーコードを生成するために使用されます。 その後、PNGバイト配列がReadメソッドに渡され、バーコードを読み取ります。 これは、AWS Lambda関数がバーコードを読み取ることができることを示しています。
Readメソッドは、BarcodeReaderOptions オブジェクトを受け入れることもでき、複数のバーコードを読む、特定のエリアをターゲットにする、非同期かつマルチスレッドで処理をする、画像補正フィルターを適用する、などの機能を有効にするためにカスタマイズできます。
メモリとタイムアウトの増加
Lambda関数に割り当てられるメモリ量は、処理されるドキュメントのサイズと同時に処理されるドキュメント数に応じて変わります。 基準として、aws-lambda-tools-defaults.json でメモリを512MBに設定し、タイムアウトを300秒に設定してください。
{
"function-memory-size": 512,
"function-timeout": 300
}
メモリが不足すると、プログラムは 'Runtime exited with error: signal: killed.'とエラーを投げます。メモリサイズを増やすことでこの問題を解決できます。 詳細については、トラブルシューティング記事「AWS Lambda - Runtime Exited Signal: Killed」を参照してください。
公開
Visual Studioで公開するには、プロジェクトを右クリックして 'AWS Lambdaに公開...' を選択し、必要な設定を構成します。 Lambdaの公開については、AWSのウェブサイトで詳しく読むことができます。
試してみましょう!
Lambda関数はLambdaコンソールまたはVisual Studioでアクティブ化できます。
よくある質問
IronBarcodeをAWS Lambdaでセットアップするにはどうすればいいですか?
IronBarcodeをAWS Lambdaにセットアップするには、Visual Studioを使用してAWS Lambdaプロジェクトを作成し、AWSSDK.S3などの必要なパッケージをインストールし、IronBarcodeのデプロイメントパスを設定し、S3バケットにバーコードを読み書きするFunctionHandlerコードを書きます。
IronBarcodeをAWS Lambdaで使用するにはどのパッケージが必要ですか?
S3バケットを管理するためのAWSSDK.S3パッケージと、デフォルトの機械学習読み取りモードを使用する場合にはMicrosoft.ML.OnnxRuntimeパッケージが必要です。
AWS Lambda用のDockerfileにIronBarcodeをインストールするにはどうすればよいですか?
Dockerfileで.NET Lambdaプロジェクトのビルド成果物をイメージにコピーし、AWS Lambda環境のためにIronBarcodeのデプロイメントパスを設定します。
AWS LambdaでのIronBarcodeにはライセンスキーが必要ですか?
はい、AWS Lambda関数内でIronBarcodeを使用するには、FunctionHandlerのコードにIronBarcodeライセンスキーを設定する必要があります。
AWS LambdaでIronBarcodeを使用してバーコードを読み取るとき、どのようなオプションをカスタマイズできますか?
AWS LambdaでIronBarcodeを使用する際、複数のバーコードを読み取ったり、特定のイメージ領域をターゲットにしたり、BarcodeReaderOptionsオブジェクトを介して非同期処理を使用するオプションをカスタマイズできます。
IronBarcodeを使用してAWS Lambdaで一時フォルダの設定をどのように扱えばよいですか?
AWS Lambda FunctionHandler内で'/tmp/'にIronBarcodeのDeploymentPathを設定することで、一時フォルダ設定を行います。
IronBarcodeを使用するAWS Lambda関数がメモリ不足になった場合、どうすればよいですか?
aws-lambda-tools-defaults.jsonの'function-memory-size'設定を使用してLambda関数に割り当てるメモリを増やし、作業負荷に適した設定にします。
IronBarcodeを使用してAWS Lambdaでバーコード画像をS3バケットにアップロードするにはどうすればよいですか?
IronBarcodeを使用してバーコードを生成し、PNGバイナリデータに変換し、Amazon S3クライアントを使用して指定されたS3バケットにこのデータをアップロードします。
OnnxRuntimeを使用せずにAWS Lambdaでバーコードを生成および読み取ることはできますか?
はい、OnnxRuntimeを使用せずにバーコードを生成および書き込むことができますが、デフォルトの機械学習モードを使用する場合、読み取りにはOnnxRuntimeが必要です。使用しない場合は非機械学習読み取りモードに切り替えてください。
IronBarcodeを使用するAWS Lambda関数を公開するにはどうすればよいですか?
Visual Studioでプロジェクトを右クリックし、「Publish to AWS Lambda」を選択します。デプロイメントに必要な設定を行い、AWSのガイドラインに従ってプロセスを完了します。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。