AWS Lambda에서 바코드 생성 및 인식

블로그 카테고리: 바코드.NET

2020/05/22

AWS Lambda는 Amazon Web Services의 일부로 Amazon에서 제공하는 이벤트 기반 서버리스 컴퓨팅 플랫폼입니다.

이 튜토리얼에서는 Visual Studio .NET 2017에서 AWS Lambda 프로젝트를 생성하고, DataMatrix 바코드 이미지를 생성하고, 생성된 이미지에서 AWS Lambda 함수의 DataMatrix 바코드를 인식하는 방법을 보여줍니다.

먼저 Visual Studio 2017을 열고 새 AWS Lambda 프로젝트를 생성해야 합니다.
Create AWS Lambda project in Visual Studio

다음으로, AWS Lambda 함수의 콘텐츠로 간단한 SQS 함수를 사용하도록 지정해야 합니다.
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에 대한 참조를 추가해야 합니다.
System.Drawing.Common은 Vintasoft.Barcode 어셈블리에 필요합니다. 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

다음은 DataMatrix 바코드가 포함된 이미지를 생성하고 생성된 이미지에서 바코드를 인식하는 AWS Lambda 함수의 C# 코드입니다.
// 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