Como Ler & Escrever Código de Barras no AWS (EC2, Lambda)
Este artigo de como fazer fornece um guia abrangente para configurar uma função AWS (EC2, Lambda) usando IronBarcode. Neste guia, você aprenderá a configurar o IronBarcode para ler e escrever códigos de barras em um bucket S3.
Como Ler & Escrever Código de Barras no AWS (EC2, Lambda)
- Baixe uma biblioteca C# para ler e escrever código de barras
- Crie e escolha o modelo de projeto
- Modifique o código do FunctionHandler.
- Configure e implemente o projeto
- Invoque a função e verifique os resultados no S3.
Instalação
Este artigo usará um bucket S3, portanto, o pacote AWSSDK.S3 é necessário.
Usando IronBarcode Zip
Se você estiver usando IronBarcode ZIP, é essencial definir a pasta temporária.
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPathDim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPathO pacote Microsoft.ML.OnnxRuntime é necessário para ler códigos de barras. Enquanto escrever códigos de barras funciona bem sem ele, o modo padrão para leitura baseia-se em aprendizado de máquina (ML). Se você mudar para um modo de leitura que não usa ML, o pacote não é necessário.
Criar um projeto AWS (EC2, Lambda)
Com o Visual Studio, criar uma instância AWS (EC2, Lambda) em contêiner é um processo fácil:
- Instale o AWS Toolkit for Visual Studio
- Selecione um 'Projeto AWS (EC2, Lambda) (.NET Core - C#)'
- Selecione um modelo ' .NET 8 (Imagem de Contêiner)' e, em seguida, selecione 'Concluir'.

Adicionar dependências de pacotes
A biblioteca IronBarcode em .NET 8 funciona no AWS (EC2, Lambda) sem a necessidade de dependências extras. Para configurá-lo, atualize o Dockerfile do projeto da seguinte forma:
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" .
Modifique o código do manipulador de funções.
Este exemplo gera um código de barras EAN8, carrega-o em um bucket S3 e lê o código de barras recém-criado. Ao usar IronBarcode ZIP, configurar a pasta temporária é crucial porque a biblioteca precisa de permissões de escrita para copiar a pasta de runtime a partir dos 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);
}
}
}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);
}
}
}Imports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronBarCode
' Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
<Assembly: LambdaSerializer(GetType(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))>
Namespace IronBarcodeZipAwsLambda
Public Class [Function]
Private Shared ReadOnly _s3Client As IAmazonS3 = 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 Function FunctionHandler(ByVal context As ILambdaContext) As Task
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
' Set your IronBarcode license key here
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
Dim filename As String = Guid.NewGuid().ToString()
Dim bucketName As String = "deploymenttestbucket"
Dim objectKey As String = $"IronBarcodeZip/{filename}.png"
Try
' Creating a barcode with EAN8 encoding
Dim 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
Dim resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData())
For Each item In resultFromByte
context.Logger.LogLine($"Barcode value is = {item.Value}")
Next item
Catch e As Exception
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
End Try
End Function
''' <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 Function UploadPngToS3Async(ByVal bucketName As String, ByVal objectKey As String, ByVal pdfBytes() As Byte) As Task
Using memoryStream As New MemoryStream(pdfBytes)
Dim request = New PutObjectRequest With {
.BucketName = bucketName,
.Key = objectKey,
.InputStream = memoryStream,
.ContentType = "image/png"
}
Await _s3Client.PutObjectAsync(request)
End Using
End Function
End Class
End NamespaceImports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronBarCode
' Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
<Assembly: LambdaSerializer(GetType(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))>
Namespace IronBarcodeZipAwsLambda
Public Class [Function]
Private Shared ReadOnly _s3Client As IAmazonS3 = 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 Function FunctionHandler(ByVal context As ILambdaContext) As Task
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
' Set your IronBarcode license key here
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
Dim filename As String = Guid.NewGuid().ToString()
Dim bucketName As String = "deploymenttestbucket"
Dim objectKey As String = $"IronBarcodeZip/{filename}.png"
Try
' Creating a barcode with EAN8 encoding
Dim 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
Dim resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData())
For Each item In resultFromByte
context.Logger.LogLine($"Barcode value is = {item.Value}")
Next item
Catch e As Exception
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
End Try
End Function
''' <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 Function UploadPngToS3Async(ByVal bucketName As String, ByVal objectKey As String, ByVal pdfBytes() As Byte) As Task
Using memoryStream As New MemoryStream(pdfBytes)
Dim request = New PutObjectRequest With {
.BucketName = bucketName,
.Key = objectKey,
.InputStream = memoryStream,
.ContentType = "image/png"
}
Await _s3Client.PutObjectAsync(request)
End Using
End Function
End Class
End NamespaceAntes do bloco try, o destino do arquivo é definido para o diretório IronBarcodeZip, com o nome gerado como um identificador único global (GUID). O método CreateBarcode é usado para gerar o código de barras. Em seguida, o array de bytes PNG é passado para o método Read para ler o código de barras. Isso demonstra que a função AWS (EC2, Lambda) é capaz de ler códigos de barras.
O método Read também aceita um objeto BarcodeReaderOptions, que você pode personalizar para habilitar recursos como leitura de múltiplos códigos de barras, focalização em áreas específicas, uso de processamento assíncrono e multithread, aplicação de filtros de correção de imagem, e muito mais.
Aumentar a memória e o tempo limite
A quantidade de memória alocada na função Lambda irá variar com base no tamanho dos documentos sendo processados e o número de documentos processados simultaneamente. Como base, defina a memória para 512 MB e o tempo limite para 300 segundos em aws-lambda-tools-defaults.json.
{
"function-memory-size": 512,
"function-timeout": 300
}
Quando a memória é insuficiente, o programa lançará o erro: 'Runtime exited with error: signal: killed.' Aumentar o tamanho da memória pode resolver esse problema. Para mais detalhes, consulte o artigo de solução de problemas: AWS (EC2, Lambda) - Runtime Exited Signal: Killed.
Publicar
Para publicar no Visual Studio, clique com o botão direito no projeto e selecione 'Publish to AWS (EC2, Lambda)...', então configure as configurações necessárias. Você pode ler mais sobre como publicar uma Lambda no site da AWS.
Experimente!
Você pode ativar a função Lambda através do console Lambda ou através do Visual Studio.
Perguntas frequentes
Como configuro o IronBarcode no AWS Lambda?
Para configurar o IronBarcode no AWS Lambda, você precisa criar um projeto AWS Lambda usando o Visual Studio, instalar pacotes necessários como o AWSSDK.S3, configurar o caminho de implantação para o IronBarcode e escrever o código FunctionHandler para ler e escrever códigos de barras em um bucket S3.
Quais pacotes são necessários para usar o IronBarcode no AWS Lambda?
Você precisa do pacote AWSSDK.S3 para gerenciar buckets S3 e o pacote Microsoft.ML.OnnxRuntime para leitura de códigos de barras, assumindo que você usa o modo de leitura de aprendizado de máquina padrão.
Como posso instalar o IronBarcode em um Dockerfile para AWS Lambda?
No seu Dockerfile, copie os artefatos de compilação do projeto .NET Lambda na imagem e configure o caminho de implantação do IronBarcode para o ambiente AWS Lambda.
É necessária uma chave de licença para o IronBarcode no AWS Lambda?
Sim, você deve definir sua chave de licença do IronBarcode no código do FunctionHandler para usar o IronBarcode em uma função AWS Lambda.
Quais opções posso personalizar ao ler códigos de barras com o IronBarcode no AWS Lambda?
Ao usar o IronBarcode no AWS Lambda, você pode personalizar opções como leitura de múltiplos códigos de barras, segmentação de áreas específicas da imagem e uso de processamento assíncrono por meio do objeto BarcodeReaderOptions.
Como posso lidar com a configuração de pasta temporária no AWS Lambda usando o IronBarcode?
Defina a configuração da pasta temporária atribuindo o DeploymentPath do IronBarcode para '/tmp/' em seu FunctionHandler do AWS Lambda.
O que devo fazer se minha função AWS Lambda usando o IronBarcode ficar sem memória?
Aumente a memória alocada para sua função Lambda usando a configuração 'function-memory-size' no aws-lambda-tools-defaults.json e certifique-se de que está configurada adequadamente para sua carga de trabalho.
Como faço para fazer o upload de uma imagem de código de barras para um bucket S3 usando o IronBarcode no AWS Lambda?
Use o IronBarcode para gerar um código de barras, converta-o em dados binários PNG e use o cliente Amazon S3 para enviar esses dados para seu bucket S3 especificado.
Posso gerar e ler códigos de barras sem usar o OnnxRuntime no AWS Lambda?
Sim, você pode gerar e escrever códigos de barras sem usar o OnnxRuntime, mas a leitura requer o OnnxRuntime se você usar o modo de aprendizado de máquina padrão. Mude para um modo de leitura não-ML se preferir não usá-lo.
Como posso publicar uma função do AWS Lambda que usa o IronBarcode?
No Visual Studio, clique com o botão direito no seu projeto e selecione 'Publicar no AWS Lambda'. Configure as configurações necessárias para implantação e siga as diretrizes da AWS para completar o processo.
Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais bem estruturados e visualmente atraentes.