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

Curtis Chau
Curtis Chau
已更新: 2026年8月2日
Amazon Lambda architecture logo

本文提供了使用 IronQR 設定 AWS Lambda 函數的詳細指南。 在本教程中,您將學習如何配置 IronQR,以便直接向 S3 儲存桶讀取和寫入二維碼。

安裝

本文將使用S3存儲桶,因此需要AWSSDK.S3套件。

立即在您的項目中開始使用 IronQR,免費試用。

第一步:
arrow pointer

建立 AWS Lambda 項目

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

  • 安裝AWS Toolkit for Visual Studio
  • 選擇“AWS Lambda 專案(.NET Core - C#)”
  • 選擇「.NET 8(容器映像)」藍圖,然後選擇「完成」。

選擇容器映像

新增包依賴項

.NET 8 中的 IronQR 函式庫可在 AWS Lambda 上執行,無需額外的相依性。 若要進行配置,請如下所示修改專案的 Dockerfile:

FROM public.ecr.aws/lambda/dotnet:8

# Install necessary packages and update repositories
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"  .
Dockerfile

修改函數處理程序程式碼

此範例產生一個二維碼,將其上傳到 S3 儲存桶,並讀取新產生的二維碼。

檔案路徑在 IronQrNuget 目錄中指定,檔案名稱使用全域唯一識別碼 (GUID)。 Write 方法根據提供的值生成QR碼,然後將生成的JPG位元組陣列傳遞給 Read 方法以讀取QR碼。 這證明該 AWS Lambda 函數能夠讀取二維碼。

using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronQr;

// 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 IronQrNuGetAwsLambda
{
    public class Function
    {
        private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

        /// <summary>
        /// Main handler for AWS Lambda
        /// </summary>
        /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
        /// <returns></returns>
        public async Task FunctionHandler(ILambdaContext context)
        {
            // Set the license key for IronQR
            IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01";

            string bucketName = "deploymenttestbucket";
            string objectKey = $"IronQrNuget/{Guid.NewGuid()}.png";

            try
            {
                // Create a QR code with the content "12345"
                var myQr = QrWriter.Write("12345");

                context.Logger.LogLine("QR created.");

                // Upload the JPG to S3
                await UploadJpgToS3Async(bucketName, objectKey, myQr.Save().ExportBytesAsJpg());

                context.Logger.LogLine($"QR uploaded successfully to {bucketName}/{objectKey}");

                // Read the QR code
                QrImageInput imageInput = new QrImageInput(myQr.Save());
                QrReader reader = new QrReader();
                var resultFromByte = reader.Read(imageInput);

                foreach (var item in resultFromByte)
                {
                    // Log the read value
                    context.Logger.LogLine($"QR value is = {item.Value}");
                }
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
            }
        }

        // Function to upload the JPG file to S3
        private async Task UploadJpgToS3Async(string bucketName, string objectKey, byte[] jpgBytes)
        {
            using (var memoryStream = new MemoryStream(jpgBytes))
            {
                var request = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = objectKey,
                    InputStream = memoryStream,
                    ContentType = "image/jpg",
                };

                await _s3Client.PutObjectAsync(request);
            }
        }
    }
}

增加記憶體和超時

Lambda 函數的記憶體分配取決於文件的大小和同時處理的文件數量。 作為起點,將記憶體設置為512 MB,並將超時設置為300秒在 aws-lambda-tools-defaults.json。

"function-memory-size" : 512,
"function-timeout" : 300
JSON

如果記憶體不足,程式將引發錯誤:「運行時錯誤退出:訊號:已終止」。增加記憶體大小可以幫助解決此問題。 有關進一步指導,請查看故障排除文章:AWS Lambda - 運行時退出信號:已殺死。

發布

要在 Visual Studio 中發布,只需右鍵單擊項目,然後選擇“發佈到 AWS Lambda...” 然後,配置所需的設定。 有關更多信息,請訪問 AWS網站。

試試看!

您可以通過Lambda控制台或通過Visual Studio激活Lambda函數。

常見問題

如何在AWS Lambda上設置IronQR?

要在AWS Lambda上設置IronQR,您需要在Visual Studio中創建一個容器化專案,添加IronQR程式庫,配置依賴項,修改Dockerfile,並以適當的記憶體和超時設定部署函數。

使用IronQR在AWS Lambda上需要哪些先決條件?

您需要Visual Studio、AWS Toolkit for Visual Studio、用於S3存儲桶互動的AWSSDK.S3封包和IronQR程式庫。

IronQR能否直接讀寫到S3存儲桶上的QR碼?

是的,IronQR可以配置為直接在AWS Lambda上讀寫到S3存儲桶上的QR碼。

如何增加IronQR在AWS Lambda上的記憶體和超時設定?

您可以通過調整aws-lambda-tools-defaults.json檔案中的'function-memory-size'和'function-timeout'字段來增加記憶體和超時設定。

.NET 8容器化專案如何整合IronQR程式庫?

IronQR的整合方法是將該程式庫添加到專案中,修改Dockerfile,並設置FunctionHandler以使用IronQR創建和讀取QR碼。

如果Lambda函數記憶體不足,我該怎麼辦?

如果函數記憶體不足,請嘗試在aws-lambda-tools-defaults.json檔案中增加記憶體分配設定並確保其具有足夠的資源以高效運行。

如何使用IronQR部署AWS Lambda函數?

通過為AWS Lambda配置專案進行函數部署,必要時增加記憶體和超時設定,並通過Visual Studio發佈專案到AWS Lambda。

IronQR在AWS Lambda上運行是否需要額外的設置?

當使用.NET 8時,除標準AWS設置外,IronQR在AWS Lambda上運行不需要額外的依賴。

在Visual Studio中將含有IronQR的專案發佈到AWS Lambda需要什麼?

要發佈,右鍵點擊專案,選擇“Publish to AWS Lambda...”,並在發佈對話框中配置必要的設定。

如何測試已部署的使用IronQR的Lambda函數?

您可以通過AWS Lambda控制台或在部署後直接從Visual Studio激活和測試Lambda函數。

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

閱讀更多

準備好開始了嗎?

NuGet 下載次數 83,364版本:2026.11剛剛發布