如何在 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;
$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);
        }
    }
}
$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 上進行條碼處理需要哪些軟體包?

對於 AWS Lambda 上的條碼處理,需要包含用於 S3 互動的 AWSSDK.S3 套件,以及用於高階機器學習條碼讀取的選用 Microsoft.ML.OnnxRuntime 套件(如果使用標準條碼讀取方法,則可能不需要此套件)。

如何修改 AWS Lambda 中用於條碼任務的 FunctionHandler 程式碼?

修改FunctionHandler程式碼,使其能夠使用 IronBarcode 建立和讀取條碼。請確保設定 IronBarcode 許可證金鑰並配置臨時資料夾,以便 IronBarcode ZIP 檔案正常運作。

如何增加處理條碼的 AWS Lambda 函數的記憶體和逾時時間?

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

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

在 Visual Studio 中右鍵點選項目,選擇“發佈到 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自訂條碼讀取,包括讀取多個條碼、定位特定區域、啟用非同步處理以及應用影像校正濾鏡。

如果在條碼處理過程中遇到「運行時因錯誤而退出:訊號:已終止」錯誤,我該怎麼辦?

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

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

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

準備好開始了嗎?
Nuget 下載 2,035,202 | 版本: 2025.12 剛剛發布