在 AWS Lambda 中生成和识别条形码

博客分类:条形码   .NET

2020/05/22

AWS Lambda 是亚马逊提供的事件驱动型无服务器计算平台,是 Amazon Web Services 的一部分。

本教程演示如何在 Visual Studio .NET 2017 中创建 AWS Lambda 项目,生成 DataMatrix 条形码图像,并在 AWS Lambda 函数中识别生成的图像中的 DataMatrix 条形码。

首先,我们需要打开 Visual Studio 2017 并创建一个新的 AWS Lambda 项目:
Create AWS Lambda project in Visual Studio

接下来,我们需要指定使用简单的 SQS 函数作为 AWS Lambda 函数的内容:
Use simple SQS function as content for AWS Lambda function in Visual Studio

以下是在 Visual Studio 2017 中创建的 AWS Lambda 项目:
AWS Lambda project in Visual Studio



接下来,我们需要为 .NET Core 添加对 System.Drawing.Common nuget 包和 Vintasoft.Barcode.dll 的引用。
Vintasoft.Barcode 组件需要 System.Drawing.Common 库。Vintasoft.Barcode 组件用于生成和识别条形码。
Add Vintasoft.Barcode.dll to AWS Lambda project in Visual Studio



接下来,我们需要打开 AWS Lambda 函数的代码:
Open code of AWS Lambda function in Visual Studio

接下来,我们需要将条形码生成和识别的代码添加到 AWS Lambda 函数中:
C# code for barcode generation and recognition using AWS Lambda function

以下是 AWS Lambda 函数的 C# 代码,它可以生成带有 DataMatrix 条形码的图像并识别生成的图像中的条形码:
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: Amazon.Lambda.Core.LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace AWSLambda1
{
    public class Function
    {

        /// <summary>
        /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
        /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the
        /// region the Lambda function is executed in.
        /// </summary>
        public Function()
        {
        }



        /// <summary>
        /// This method is called for every Lambda invocation. This method takes in an SQS event object and can be used
        /// to respond to SQS messages.
        /// </summary>
        public async System.Threading.Tasks.Task FunctionHandler(Amazon.Lambda.SQSEvents.SQSEvent evnt, Amazon.Lambda.Core.ILambdaContext context)
        {
            foreach (var message in evnt.Records)
            {
                await ProcessMessageAsync(message, context);
            }
        }

        private async System.Threading.Tasks.Task ProcessMessageAsync(Amazon.Lambda.SQSEvents.SQSEvent.SQSMessage message, Amazon.Lambda.Core.ILambdaContext context)
        {
            context.Logger.LogLine($"Processed message {message.Body}");

            try
            {
                // create memory stream, where image with barcode will be stored
                using (System.IO.MemoryStream mem = new System.IO.MemoryStream())
                {
                    // create the barcode writer
                    Vintasoft.Barcode.BarcodeWriter barcodeWriter = new Vintasoft.Barcode.BarcodeWriter();
                    // specify that DataMatrix barcode must be created
                    barcodeWriter.Settings.Barcode = Vintasoft.Barcode.BarcodeType.DataMatrix;
                    // specify the barcode value
                    barcodeWriter.Settings.Value = "1234567890987654321";
                    // generate barcode image and save to the memory stream as PNG file
                    barcodeWriter.SaveBarcodeAsImage(mem, Vintasoft.Barcode.BarcodeImageFormat.Png);

                    // create the barcode reader
                    using (Vintasoft.Barcode.BarcodeReader barcodeReader = new Vintasoft.Barcode.BarcodeReader())
                    {
                        // specify that reader must search for DataMatrix barcodes
                        barcodeReader.Settings.ScanBarcodeTypes = Vintasoft.Barcode.BarcodeType.DataMatrix;
                        // specify that reader must search horizontal barcodes only
                        barcodeReader.Settings.ScanDirection = Vintasoft.Barcode.ScanDirection.Horizontal;

                        // read barcodes from image
                        Vintasoft.Barcode.IBarcodeInfo[] infos = barcodeReader.ReadBarcodes(mem);

                        // if barcodes are not detected
                        if (infos.Length == 0)
                        {
                            context.Logger.LogLine($"No barcodes found.");
                        }
                        // if barcodes are detected
                        else
                        {
                            // get information about searched barcodes

                            for (int i = 0; i &lt; infos.Length; i++)
                            {
                                Vintasoft.Barcode.IBarcodeInfo info = infos[i];
                                context.Logger.LogLine(string.Format("Barcode: Type={0}, Value={1}", info.BarcodeType, info.Value));
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                context.Logger.LogLine(string.Format("Error: {0}", ex.Message));
            }

            await System.Threading.Tasks.Task.CompletedTask;
        }
    }
}



最后,我们需要在 AWS .NET Mock Lambda 测试工具中运行我们的 AWS Lambda 函数:
Run AWS Lambda function in AWS .NET Mock Lambda Test Tool

向我们的 AWS Lambda 函数发送 SQS 请求:
Send a SQS request to our AWS Lambda function

并查看使用 AWS Lambda 函数进行条形码识别的结果:
Result of barcode recognition using AWS Lambda function