如何在 AWS Lambda 上读写 BarCode

查克尼特·宾
查克尼特·宾
2023年十一月21日
更新 2024年十月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 上读写 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
$vbLabelText   $csharpLabel

需要Microsoft.ML.OnnxRuntime软件包来读取条形码。 虽然在没有它的情况下写入条形码效果很好,但读取的默认模式依赖于机器学习(ML)。 如果您切换到不使用 ML 的阅读模式,则不需要该软件包。

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

第一步:
green arrow pointer

创建 AWS Lambda 项目

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

  • 安装AWS Toolkit for Visual Studio
  • 选择“AWS Lambda 项目(.NET Core - C#)”
  • 选择一个“.NET 8(容器镜像)”蓝图,然后选择“完成”。

    选择容器镜像

添加软件包依赖关系

.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
$vbLabelText   $csharpLabel

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

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...",然后配置必要的设置。 您可以在AWS 网站上阅读更多关于发布 Lambda 的信息。

试用!

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

查克尼特·宾
软件工程师
Chaknith 负责 IronXL 和 IronBarcode 的工作。他在 C# 和 .NET 方面拥有深厚的专业知识,帮助改进软件并支持客户。他从用户互动中获得的洞察力,有助于提升产品、文档和整体体验。