如何在 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 = awsTmpPath读取条形码需要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)' 蓝图,然后选择 '完成'。

添加包依赖项
IronBarcode 库在 .NET 8 中无需额外依赖项即可在 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 时,配置临时文件夹至关重要,因为库需要写入权限以从 DLLs 拷贝运行时文件夹。
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 Namespace在 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 中发布,右键单击项目并选择 'Publish to AWS Lambda...',然后配置必要的设置。 您可以在AWS网站上阅读有关发布Lambda的更多信息。
试一试!
您可以通过Lambda控制台或通过Visual Studio激活Lambda函数。
常见问题
如何在AWS Lambda上设置IronBarcode?
要在AWS Lambda上设置IronBarcode,您需要使用Visual Studio创建一个AWS Lambda项目,安装必要的包如AWSSDK.S3,配置IronBarcode的部署路径,并编写FunctionHandler代码以读取和写入S3存储桶中的条码。
在AWS Lambda上使用IronBarcode需要哪些包?
您需要AWSSDK.S3包来管理S3存储桶以及用于条码读取的Microsoft.ML.OnnxRuntime包,假设您使用默认的机器学习读取模式。
如何在用于AWS Lambda的Dockerfile中安装IronBarcode?
在您的Dockerfile中,将.NET Lambda项目的构建工件复制到镜像中并配置IronBarcode在AWS Lambda环境中的部署路径。
在AWS Lambda上使用IronBarcode需要许可证密钥吗?
是的,您必须在FunctionHandler的代码中设置IronBarcode许可证密钥以便在AWS Lambda函数中使用IronBarcode。
使用IronBarcode在AWS Lambda中读取条码时可以自定义哪些选项?
在AWS Lambda中使用IronBarcode时,您可以自定义选项,比如读取多个条码、定位特定图像区域以及使用异步处理,这些都可以通过BarcodeReaderOptions对象进行设置。
如何在AWS Lambda中使用IronBarcode处理临时文件夹配置?
通过在您的AWS Lambda FunctionHandler中将IronBarcode的DeploymentPath配置为'/tmp/'来设置临时文件夹配置。
如果我的AWS Lambda函数使用IronBarcode内存不足,我该怎么做?
通过在aws-lambda-tools-defaults.json中的'function-memory-size'设置增加Lambda函数的分配内存,并确保其适合您的工作负载。
如何使用IronBarcode在AWS Lambda上将条码图像上传到S3存储桶?
使用IronBarcode生成条码,将其转换为PNG二进制数据,然后使用Amazon S3客户端将这些数据上传到您指定的S3存储桶中。
我可以在AWS Lambda上不使用OnnxRuntime生成和读取条码吗?
是的,您可以在不使用OnnxRuntime的情况下生成和写入条码,但如果使用默认的机器学习模式,读取需要OnnxRuntime。如果您不想使用它,请切换到非机器学习读取模式。
如何发布一个使用IronBarcode的AWS Lambda函数?
在Visual Studio中,右键单击您的项目并选择'发布到AWS Lambda'。配置必要的设置以进行部署,并按照AWS指南完成该过程。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。