如何在 AWS Lambda 上读写 BarCode

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to 如何在 AWS Lambda 上读写 BarCode

本文将全面介绍如何使用 IronBarcode 设置 AWS Lambda 函数。 在本指南中,您将学习如何配置 IronBarcode 从 S3 存储桶读取条码并将其写入 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
VB   C#

这 *Microsoft.ML.OnnxRuntime读取 BarCode 需要 * 软件包。 虽然不使用条形码也能正常书写,但读取条形码的默认模式依赖于机器学习(ML). 如果您切换到不使用 ML 的阅读模式,则不需要该软件包。

立即在您的项目中开始使用IronBarcode,并享受免费试用。

第一步:
green arrow pointer

创建 AWS Lambda 项目

使用 Visual Studio,创建容器化 AWS Lambda 是一个简单的过程:

添加软件包依赖关系

.NET 8 中的 IronBarcode 库可在 AWS Lambda 上运行,无需额外依赖。 设置方法如下:更新项目的 Dockerfile:


FROM public.ecr.aws/lambda/dotnet:8

# 安装必要的软件包

运行 dnf update -y

WORKDIR /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 文件。

复制 "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);

    /// <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
VB   C#

在 try 代码块之前,文件目标地址被设置为 IronBarcodeZip 目录,文件名作为全局唯一标识符生成(GUID). 使用 CreateBarcode 方法生成条形码。 之后,将 PNG 字节数组传递给 Read 方法以读取条形码。 这表明 AWS Lambda 函数能够读取 BarCode。

Read "方法还接受一个BarcodeReaderOptions对象,您可以自定义该对象以启用以下功能读取多个 BarCode, 针对特定领域, 使用异步和多线程处理, 应用图像校正过滤器以及更多。

增加内存和超时

Lambda 函数分配的内存量将根据正在处理的文档大小和同时处理的文档数量而变化。 作为基准,在 aws-lambda-tools-defaults.json 中将内存设置为 512 MB,超时时间设置为 300 秒。


"function-memory-size" : 512,

"function-timeout" : 300

当内存不足时,程序会出现错误:"Runtime exited with error: signal: killed"。增加内存大小可以解决这个问题。 有关详细信息,请参阅故障排除文章:AWS Lambda - 运行时退出信号:已杀死.

出版

要在 Visual Studio 中发布,请右键单击项目并选择 "发布到 AWS Lambda...",然后配置必要的设置。 您可以了解更多有关发布 Lambda 的信息。AWS 网站.

试用!

您可以通过以下方式激活 Lambda 函数:Lambda 控制台或通过 Visual Studio。