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

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to 如何在 AWS Lambda 上讀取和寫入二維碼

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

安裝

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

立即開始在您的專案中使用 IronQR,享受免費試用。

第一步:
green arrow pointer

建立 AWS Lambda 項目

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

選擇容器影像

新增包依賴項

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

修改函數處理程序程式碼

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

檔案路徑在 IronQrNuget 目錄中指定,檔案名稱使用全域唯一識別碼 (GUID)。 Write方法根據提供的值產生二維碼,然後將產生的 JPG 位元組數組傳遞給Read方法以讀取二維碼。 這證明該 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);
            }
        }
    }
}
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);
            }
        }
    }
}
$vbLabelText   $csharpLabel

增加記憶體和超時

Lambda 函數的記憶體分配取決於文件的大小和同時處理的文件數量。 首先,在aws-lambda-tools-defaults.json中將記憶體設定為 512 MB,逾時設定為 300 秒。

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

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

發布

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

試試看!

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

常見問題解答

如何將二維碼庫整合到我在 AWS Lambda 上的 C# 專案中?

您可以透過下載 IronQR 庫、使用 Visual Studio 建立容器化的 AWS Lambda 專案以及配置環境以支援二維碼操作,將 IronQR 等二維碼庫整合到 AWS Lambda 上的 C# 專案中。

如何配置 IronQR 以用於 AWS Lambda?

透過在 Visual Studio 中設定容器化專案範本、修改 Dockerfile、更新 FunctionHandler 以及調整記憶體和逾時設定來配置 IronQR for AWS Lambda,以確保流暢運行。

如何使用 C# 函式庫在 AWS S3 上管理二維碼?

使用 IronQR,您可以管理二維碼,包括建立二維碼、上傳二維碼以及從 AWS S3 儲存桶讀取二維碼。這需要將 IronQR 庫與 AWSSDK.S3 套件結合使用,以處理 S3 儲存桶的操作。

如果我的使用 IronQR 的 AWS Lambda 函數運作不佳,我該怎麼辦?

如果您的 AWS Lambda 函數運作不佳,請考慮增加aws-lambda-tools-defaults.json檔案中的記憶體和逾時設置,以便為該函數分配更多資源。

如何將 C# Lambda 函數部署到 AWS?

使用 Visual Studio 的「發佈到 AWS Lambda...」選項,配置必要的設置,並利用 AWS Toolkit 進行部署,即可將 C# Lambda 函數部署到 AWS。

是否可以在 Visual Studio 中測試我的 AWS Lambda 函數?

是的,您可以使用 AWS Toolkit 在 Visual Studio 中測試 AWS Lambda 函數,方法是呼叫函數並在您的開發環境中直接驗證其輸出。

如何排查 AWS Lambda 函數的記憶體問題?

要排查記憶體問題,請在aws-lambda-tools-defaults.json檔案中增加函數的記憶體分配,並在重新部署後監控函數的效能。

在 AWS Lambda 專案中修改 Dockerfile 的重要性是什麼?

在 AWS Lambda 專案中修改 Dockerfile 對於正確設定環境至關重要,包括更新儲存庫和複製必要的建置工件,以便函數能夠正確執行。

如何確保我的 AWS Lambda 函數能夠有效率地處理二維碼操作?

透過優化記憶體和逾時設定、使用 IronQR 等合適的庫以及正確配置 Dockerfile 和專案設置,確保您的 AWS Lambda 函數能夠有效率地處理二維碼操作。

我可以在 AWS Lambda 中自動產生和檢索二維碼嗎?

是的,您可以使用 IronQR 在 AWS Lambda 中自動產生和擷取二維碼。該庫允許您以程式設計方式建立二維碼,將其上傳到 S3,並在需要時將其讀取回來。

柯蒂斯·週
技術撰稿人

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

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

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