如何在 AWS Lambda 上讀取與寫入 BarCode

This article was translated from English: Does it need improvement?
Translated
View the article in English
AWS Lambda

這篇操作指南提供了一套完整的指引,說明如何使用 IronBarcode 設定 AWS Lambda 函式。 在本指南中,您將學習如何設定 IronBarcode,使其能夠從 S3 儲存桶讀取 BarCode,並將 BarCode 寫入 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

讀取 BARCODE 需安裝 Microsoft.ML.OnnxRuntime 套件。 雖然在寫入BarCode時無需此功能即可正常運作,但讀取BarCode的預設模式仰賴機器學習(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"  .

修改 FunctionHandler 程式碼

此範例會產生一個 EAN8 BARCODE,將其上傳至 S3 儲存桶,並讀取新建立的 BARCODE。 使用 IronBarcode ZIP 時,設定暫存資料夾至關重要,因為 IronBarcode程式庫需要寫入權限,才能將 DLL 中的執行時資料夾複製過來。

using Amazon.Lambda.Co/re;
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.Co/re;
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(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
            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(bucketName As String, objectKey As String, pdfBytes As Byte()) As Task
            Using memoryStream As New MemoryStream(pdfBytes)
                Dim request As 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 方法來生成 BARCODE。 隨後,將 PNG 位元組陣列傳遞給 Read 方法以讀取 BARCODE。 這顯示 AWS Lambda 函式具備讀取 BARCODE 的能力。

Read 方法亦接受 BarCodeReaderOptions 物件,您可以透過自訂該物件來啟用各項功能,例如讀取多個 BARCODE鎖定特定區域使用非同步與多執行緒處理套用影像校正濾鏡等,以及更多功能。

增加記憶體與超時設定

Lambda 函式中分配的記憶體量將根據處理中文件的大小以及同時處理的文件數量而有所不同。 作為基準設定,請在 aws-lambda-tools-defaults.json 中將記憶體設為 512 MB,並將超時時間設為 300 秒。

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

當記憶體不足時,程式會拋出錯誤訊息:"執行時因錯誤而終止:訊號:被終止。"增加記憶體大小可解決此問題。 如需更多詳細資訊,請參閱疑難排解文章:AWS Lambda - 執行時退出訊號:Killed

發佈

要在 Visual Studio 中發佈,請右鍵點擊專案並選擇"發佈至 AWS Lambda...",然後配置必要的設定。 您可以在 AWS 網站上閱讀更多關於發佈 Lambda 的資訊。

立即試用!

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

常見問題

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

要在AWS Lambda上設置條碼讀取和寫入,通過下載IronBarcode程式庫並使用Visual Studio建立AWS Lambda專案。修改FunctionHandler程式碼以處理條碼操作,配置專案設定並部署。確保包含必要的套件依賴,如AWSSDK.S3。

AWS Lambda上的條碼處理由哪些套件組成?

對於AWS Lambda上的條碼處理,包含用於S3交互的AWSSDK.S3套件,選擇性地包含用於先進機器學習條碼讀取的Microsoft.ML.OnnxRuntime套件,這在使用標準條碼讀取方法時可能不需要。

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

修改FunctionHandler程式碼以使用IronBarcode創建和讀取條碼。確保您設定IronBarcode的授權金鑰並配置臨時資料夾以妥善運行IronBarcode ZIP文件。

如何增加處理條碼的AWS Lambda函數的內存和超時?

通過在aws-lambda-tools-defaults.json文件中設定函數內存大小為512 MB及函數超時為300秒,以滿足使用IronBarcode進行條碼處理的需求。

如何使用Visual Studio為條碼處理發布Lambda函數?

通過在Visual Studio中右鍵單擊專案,選擇“Publish to AWS Lambda...”並配置設定來發布Lambda函數。遵循AWS文檔以獲取詳細步驟,確保正確設置IronBarcode。

如何測試已部署的AWS Lambda函數以進行條碼操作?

通過AWS Lambda控制台或直接從Visual Studio啟動來測試Lambda函數,確保IronBarcode正常運行並按預期執行條碼處理任務。

Dockerfile在AWS Lambda上設置條碼處理中起什麼作用?

Dockerfile幫助更新必要的套件並將.NET Lambda專案的構造元件複製到影像中,從而促進在AWS Lambda上與IronBarcode的無縫條碼處理。

為什麼在AWS Lambda上使用條碼程式庫時設定臨時資料夾很重要?

設定臨時資料夾是必不可少的,因為IronBarcode需要寫入許可以進行ZIP操作,確保運行時資料夾從DLL中正確複製以在AWS Lambda上順利運行。

我可以在AWS Lambda上自定義條碼讀取嗎?

是的,IronBarcode允許使用BarcodeReaderOptions自定義條碼讀取,其中包括讀取多個條碼,針對特定區域,啟用異步處理,並應用圖像修正過濾器。

如果在條碼處理過程中遇到“Runtime exited with error: signal: killed”錯誤,我該怎麼做?

此錯誤表明分配的內存不足。增加Lambda函數在aws-lambda-tools-defaults.json文件中的內存以解決該問題,同時使用IronBarcode。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備好開始了嗎?
Nuget 下載 2,240,258 | 版本: 2026.5 just released
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。