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

This article was translated from English: Does it need improvement?
Translated
View the article in English
AWS Lambda

このハウツー記事は、IronBarcodeを使用してAWS Lambda関数をセットアップするための包括的なガイドを提供します。 このガイドでは、IronBarcodeを設定してS3バケットからバーコードを読み取ったり書き込んだりする方法を学びます。

インストール

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

IronBarcode Zipの使用

IronBarcode ZIPを使用する場合、一時フォルダを設定することが重要です。

var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
$vbLabelText   $csharpLabel

バーコードを読み取るには、Microsoft.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 Namespace
$vbLabelText   $csharpLabel

tryブロックの前に、ファイルの宛先は IronBarcodeZipディレクトリに設定され、名前はグローバルユニーク識別子(GUID)として生成されます。 CreateBarcodeメソッドを使用してバーコードを生成します。 その後、PNGバイト配列をReadメソッドに渡してバーコードを読み取ります。 これは、AWS Lambda関数がバーコードを読み取ることができることを示しています。

Readメソッドは、BarcodeReaderOptionsオブジェクトも受け入れ、複数のバーコードを読み取る特定の領域をターゲット非同期およびマルチスレッド処理を使用画像補正フィルターの適用などの機能を有効にするためにカスタマイズできます。

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

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

{
    "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コンソールまたはVisual Studioを使用して、Lambda関数をアクティブにすることができます。

よくある質問

AWS Lambdaでのバーコードの読み取りと書き込みをどのように設定しますか?

AWS Lambdaでのバーコードの読み取りと書き込みを設定するには、IronBarcodeライブラリをダウンロードしてVisual StudioでAWS Lambdaプロジェクトを作成します。バーコード操作を処理するためにFunctionHandlerコードを修正し、プロジェクト設定を構成してデプロイします。AWSSDK.S3などの必要なパッケージ依存関係が含まれていることを確認してください。

AWS Lambdaでのバーコード処理に必要なパッケージは何ですか?

AWS Lambdaでのバーコード処理には、S3とのやり取りのためにAWSSDK.S3パッケージを含め、標準のバーコード読み取り方法を使用する場合は必要ないかもしれませんが、高度な機械学習バーコード読み取りのためにオプションでMicrosoft.ML.OnnxRuntimeパッケージを含めます。

AWS Lambdaでのバーコードタスク用にFunctionHandlerコードをどのように修正できますか?

IronBarcodeを使用してバーコードを生成および読み取るためにFunctionHandlerコードを修正します。IronBarcodeのライセンスキーを設定し、IronBarcode ZIPファイルの適切な動作のために一時フォルダの設定を行います。

バーコードを扱うAWS Lambda関数のメモリとタイムアウトをどのように増加させますか?

aws-lambda-tools-defaults.jsonファイルでfunction-memory-sizeを512MBに、function-timeoutを300秒に設定して、IronBarcodeによるバーコード処理のニーズに対応します。

バーコード処理のためにVisual Studioを使用してLambda関数を公開するにはどうすればよいですか?

Visual Studioでプロジェクトを右クリックし、「AWS Lambdaに公開...」を選択して、設定を構成します。詳細な手順はAWSドキュメントに従い、IronBarcodeが正しく設定されていることを確認します。

バーコード操作用のデプロイされたAWS Lambda関数をどのようにテストできますか?

AWS Lambdaコンソールを通じて、または直接Visual Studioから関数を起動してLambda関数をテストし、IronBarcodeが正しく動作し、バーコード処理タスクが期待どおりに実行されることを確認します。

AWS Lambdaでのバーコード処理のセットアップにおけるDockerfileの役割は何ですか?

Dockerfileは、必要なパッケージの更新と.NET Lambdaプロジェクトのビルドアーティファクトをイメージにコピーするのに役立ち、AWS LambdaでIronBarcodeとのシームレスなバーコード処理を可能にします。

AWS Lambdaでバーコードライブラリを使用する際に一時フォルダを設定することが重要なのはなぜですか?

一時フォルダを設定することが重要なのは、IronBarcodeがZIP操作の書き込み権限を必要とし、DLLからランタイムフォルダが正しくコピーされることを保証し、AWS Lambda上でのスムーズな動作を可能にするためです。

AWS Lambdaのバーコード読み取りをカスタマイズできますか?

はい、IronBarcodeを使用すると、BarcodeReaderOptionsを使用して複数のバーコードを読み取ったり、特定のエリアを狙ったり、非同期処理を有効にしたり、画像補正フィルターを適用することでバーコード読み取りをカスタマイズできます。

バーコード処理中に'Runtime exited with error: signal: killed'エラーが発生した場合はどうすればよいですか?

このエラーはメモリの割り当てが不十分であることを示します。IronBarcodeを使用しながらこの問題を解決するために、aws-lambda-tools-defaults.jsonファイルでLambda関数のメモリを増やします。

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

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

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

準備はできましたか?
Nuget ダウンロード 1,979,979 | Version: 2025.11 リリース