如何在 AWS Lambda 上讀取和寫入條碼

This article was translated from English: Does it need improvement?
Translated
View the article in English
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)。 如果切換到不使用 ML 的閱讀模式,則不需要該軟體包。

建立 AWS Lambda 項目

使用 Visual Studio,建立容器化的 AWS Lambda 函數非常簡單:

選擇容器影像

新增包依賴項

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

在 try 程式碼區塊之前,檔案目標位置設定為 IronBarcodeZip 目錄,檔案名稱由全域唯一識別碼 (GUID) 產生。 CreateBarcode方法用於產生條碼。 之後,將 PNG 位元組數組傳遞給Read方法來讀取條碼。 這證明 AWS Lambda 函數能夠讀取條碼。

Read方法也接受一個BarcodeReaderOptions對象,您可以對其進行自訂以啟用讀取多個條碼定位特定區域使用非同步和多執行緒處理套用影像校正濾鏡等功能。

增加記憶體和超時

Lambda 函數中分配的記憶體量將根據正在處理的文件的大小和同時處理的文件數量而變化。 作為基準,在aws-lambda-tools-defaults.json中將記憶體設為 512 MB,逾時設為 300 秒。

{
    "function-memory-size": 512,
    "function-timeout": 300
}

當記憶體不足時,程式會拋出錯誤:"運行時錯誤退出:訊號:終止"。增加記憶體大小可以解決此問題。 如需更多詳細信息,請參閱故障排除文章: AWS Lambda - 運行時退出訊號:已終止

發布

若要在 Visual Studio 中發布,請右鍵按一下專案並選擇"發佈到 AWS Lambda...",然後配置必要的設定。 您可以在AWS 網站上閱讀更多關於發布 Lambda 函數的資訊。

試試看!

您可以透過Lambda 控制台或 Visual Studio 啟動 Lambda 函數。

常見問題解答

如何在 AWS Lambda 上設定條碼讀寫?

要在 AWS Lambda 上設定條碼讀寫,請使用 IronBarcode 函式庫,方法是下載該函式庫,並使用 Visual Studio 建立 AWS Lambda 專案。修改 FunctionHandler 程式碼以處理條碼作業,設定專案設定,並部署它。確保包含必要的套件相依性,例如 AWSSDK.S3。

AWS Lambda 上的 BarCode 處理需要哪些套件?

若要在 AWS Lambda 上進行條碼處理,請包含 AWSSDK.S3 套件以進行 S3 互動,並可選擇 Microsoft.ML.OnnxRuntime 套件以進行進階機器學習條碼讀取,若使用標準條碼讀取方法,則可能不需要此套件。

如何修改 AWS Lambda 中的 FunctionHandler 程式碼以執行 BarCode 任務?

修改 FunctionHandler 程式碼,以使用 IronBarcode 建立和讀取條碼。確保設定 IronBarcode 授權金鑰,並設定暫存資料夾,以正確操作 IronBarcode ZIP 檔案。

如何增加處理 BarCode 的 AWS Lambda 函式的記憶體和超時?

調整 aws-lambda-tools-defaults.json 檔案中的記憶體和逾時設定,將 function-memory-size 設定為 512 MB,function-timeout 設定為 300 秒,以迎合 IronBarcode 的條碼處理需求。

如何使用 Visual Studio 發佈 Lambda 函式以進行 BarCode 處理?

在 Visual Studio 中右擊專案,選擇「發佈至 AWS Lambda...」並設定設定,即可發佈 Lambda 函式。遵循 AWS 文件的詳細步驟,確保 IronBarcode 設定正確。

如何測試已部署的 AWS Lambda 函式以進行 BarCode 作業?

透過 AWS Lambda 主控台或直接從 Visual Studio 啟動 Lambda 函式進行測試,確保 IronBarcode 運作正常,且條碼處理任務如期執行。

在 AWS Lambda 上設定條碼處理時,Dockerfile 的作用是什麼?

Dockerfile 有助於更新必要的套件,並將 .NET Lambda 專案的建立工件複製到映像中,方便在 AWS Lambda 上使用 IronBarcode 進行無縫條碼處理。

在 AWS Lambda 上使用 BarCode 库时,为什么设置临时文件夹很重要?

設定臨時資料夾非常重要,因為 IronBarcode 需要 ZIP 作業的寫入權限,以確保從 DLL 正確複製運行時資料夾,以便在 AWS Lambda 上順暢運作。

我可以在 AWS Lambda 上自訂 BarCode 讀取功能嗎?

是的,IronBarcode 允許使用 BarcodeReaderOptions 自訂條碼讀取,其中包括讀取多個條碼、針對特定區域、啟用異步處理,以及套用影像修正篩選器。

如果在處理 BarCode 時遇到「Runtime exited with error: signal: killed」錯誤,該怎麼辦?

此錯誤顯示記憶體分配不足。在使用 IronBarcode 時,增加 aws-lambda-tools-defaults.json 檔案中 Lambda 函式的記憶體以解決問題。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 1,979,979 | Version: 2025.11 剛發表