IRONSOFTWAREHOME

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

Curtis Chau
Curtis Chau
Updated: 2026年6月4日
AWS Lambda

此操作文章提供了一個綜合指南,教您如何使用IronBarcode設置AWS Lambda函式。 在本指南中,您將學習如何配置IronBarcode從S3桶中讀取和寫入條碼。

安裝

本文將使用S3桶,因此需要**AWSSDK.S3**包。

使用IronBarcode Zip

如果您使用IronBarcode ZIP,則需要設置臨時文件夾。

var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;

讀取條碼需要**Microsoft.ML.OnnxRuntime**包。 雖然寫入條碼不需要它,但預設的讀取模式依賴於機器學習(ML)。 如果您切換到不使用ML的讀取模式,則不需要該包。

建立AWS Lambda專案

使用Visual Studio,建立容器化的AWS Lambda是一個簡單的過程:

  • 安裝Visual Studio的AWS Toolkit
  • 選擇"AWS Lambda Project (.NET Core - C#)"
  • 選擇".NET 8 (Container Image)"藍圖,然後選擇"完成"。

選擇容器映像

新增包依賴性

.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"  .
Text

修改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);
        }
    }
}

在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
}
JSON

當記憶體不足時,程式將拋出錯誤:"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上設置條形碼的讀取和寫入?

要在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文件中調整記憶體和超時設置,將function-memory-size設置為512 MB,將function-timeout設置為300秒,以滿足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專案的構建工件複製到圖像中,從而使IronBarcode在AWS Lambda上的條形碼處理更加順暢。

在AWS Lambda上使用條形碼庫時為何設置臨時文件夾很重要?

設置臨時文件夾是必要的,因為IronBarcode需要寫入權限來進行ZIP操作,確保從DLLs正確複製運行時間文件夾,以便在AWS Lambda上順利運行。

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

可以,IronBarcode允許使用BarcodeReaderOptions自定義條形碼讀取,這包括讀取多個條形碼、定位特定區域、啟用異步處理和應用圖像校正過濾器。

在條形碼處理期間遇到“Runtime exited with error: signal: killed”錯誤時該怎麼辦?

此錯誤表明記憶體分配不足。在aws-lambda-tools-defaults.json文件中增加Lambda功能的記憶體以解決此問題,當使用IronBarcode時。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

準備好開始了嗎?

Nuget Downloads 2,422,100版本:2026.9剛剛發布

立即獲取您的免費30天試用金鑰
不需要信用卡或帳戶建立
C# NuGet程式庫,用於PDF
通過NuGet安裝

版本: 2026.9

PM > Install-Package BarCode
nuget.org/packages/BarCode/
  1. 在解決方案資源管理器中,右鍵點擊References,管理NuGet包
  2. 選擇瀏覽並搜尋"IronBarCode"
  3. 選擇包並安裝
C# PDF DLL
下載DLL

版本: 2026.9

  1. 下載並解壓IronBarCode至您的Solution目錄中的~/Libs等位置
  2. 在Visual Studio解決方案資源管理器中右鍵點擊References,選擇瀏覽,"IronBarCode.dll"

$999起的授權費用

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費即時演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲取您的無義務諮詢
完成下方表單或發送電子郵件至sales@ironsoftware.com
您的詳細資訊將始終保密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立