AWS Lambdaでバーコードを読み取りおよび書き込む方法

チャクニット・ビン
チャクニット・ビン
2023年11月21日
更新済み 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でバーコードを読み取りおよび書き込む方法

このハウツー記事は、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を使用しないリーディングモードに切り替える場合、そのパッケージは必要ありません。

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

最初のステップ:
green arrow pointer

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

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

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

    コンテナイメージを選択

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

.NET 8のIronBarcodeライブラリは、追加の依存関係なしで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"  .

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

この例では、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);

    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    /// <returns></returns>
    public async Task FunctionHandler(ILambdaContext context)
    {
        var awsTmpPath = @"/tmp/";
        IronBarCode.Installation.DeploymentPath = awsTmpPath;

        IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";

        string filename = Guid.NewGuid().ToString();

        string bucketName = "deploymenttestbucket";
        string objectKey = $"IronBarcodeZip/{filename}.png";

        try
        {
            // Creating a barcode is as simple as:
            var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);

            // Use pdfData (byte array) as needed
            context.Logger.LogLine($"Barocde created.");

            // Upload the PDF to S3
            await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());

            context.Logger.LogLine($"Barocde uploaded successfully to {bucketName}/{objectKey}");

            var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());

            foreach (var item in resultFromByte)
            {
                // Log the read value out
                context.Logger.LogLine($"Barcode value is = {item.Value}");
            }
        }
        catch (Exception e)
        {
            context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
        }
    }
    // Function to upload the PNG file to S3
    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);

    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    /// <returns></returns>
    public async Task FunctionHandler(ILambdaContext context)
    {
        var awsTmpPath = @"/tmp/";
        IronBarCode.Installation.DeploymentPath = awsTmpPath;

        IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";

        string filename = Guid.NewGuid().ToString();

        string bucketName = "deploymenttestbucket";
        string objectKey = $"IronBarcodeZip/{filename}.png";

        try
        {
            // Creating a barcode is as simple as:
            var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);

            // Use pdfData (byte array) as needed
            context.Logger.LogLine($"Barocde created.");

            // Upload the PDF to S3
            await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());

            context.Logger.LogLine($"Barocde uploaded successfully to {bucketName}/{objectKey}");

            var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());

            foreach (var item in resultFromByte)
            {
                // Log the read value out
                context.Logger.LogLine($"Barcode value is = {item.Value}");
            }
        }
        catch (Exception e)
        {
            context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
        }
    }
    // Function to upload the PNG file to S3
    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)

		''' <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
			Dim awsTmpPath = "/tmp/"
			IronBarCode.Installation.DeploymentPath = awsTmpPath

			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 is as simple as:
				Dim myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8)

				' Use pdfData (byte array) as needed
				context.Logger.LogLine($"Barocde created.")

				' Upload the PDF to S3
				Await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData())

				context.Logger.LogLine($"Barocde uploaded successfully to {bucketName}/{objectKey}")

				Dim resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData())

				For Each item In resultFromByte
					' Log the read value out
					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
		' Function to upload the PNG file to S3
		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 - ランタイム終了シグナル: Killed

出版

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

お試しください!

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

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