如何在 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)。 如果切換到不使用 ML 的閱讀模式,則不需要該軟體包。
建立 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
# 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" .
修改函數處理程序程式碼
此範例產生 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 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
}
當記憶體不足時,程式會拋出錯誤:「運行時錯誤退出:訊號:終止」。增加記憶體大小可以解決此問題。 如需更多詳情,請參考故障排除文章:AWS Lambda - 運行時間結束信號:被終止。
發布
若要在 Visual Studio 中發布,請右鍵按一下專案並選擇“發佈到 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專案的建置工件複製到映像中,並配置AWS Lambda環境中的IronBarcode部署路徑。
在AWS Lambda上使用IronBarcode需要授權金鑰嗎?
是的,您必須在FunctionHandler的程式碼中設置您的IronBarcode授權金鑰,才能在AWS Lambda函數中使用IronBarcode。
在AWS Lambda上使用IronBarcode讀取條碼時可以自定義哪些選項?
在AWS Lambda上使用IronBarcode時,您可以自定義選項,例如讀取多個條碼、針對特定圖像區域,以及通過BarcodeReaderOptions物件使用非同步處理。
如何使用IronBarcode在AWS Lambda中處理臨時資料夾配置?
藉由在您的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,如果您使用默認的機器學習模式。如果您不想要使用它,可以切換到非ML讀取模式。
如何發布用於AWS Lambda的IronBarcode函數?
在Visual Studio中,右鍵單擊您的專案並選擇'發佈到AWS Lambda'。配置部署所需的設置,並按照AWS指南完成過程。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。