Lesen und Schreiben von BarCode auf AWS Lambda
Dieser Leitartikel bietet eine umfassende Anleitung zur Einrichtung einer AWS Lambda-Funktion mit IronBarcode. In diesem Leitfaden lernen Sie, wie Sie IronBarcode konfigurieren, um von einem S3-Bucket Barcodes zu lesen und Barcodes darauf zu schreiben.
Lesen und Schreiben von BarCodes in AWS Lambda
- Laden Sie eine C#-Bibliothek zum Lesen und Schreiben von Barcodes herunter
- Erstellen und wählen Sie die Projektvorlage
- Ändern Sie den FunctionHandler-Code
- Konfigurieren und stellen Sie das Projekt bereit
- Rufen Sie die Funktion auf und überprüfen Sie die Ergebnisse in S3
Installation
Dieser Artikel wird einen S3-Bucket verwenden, daher wird das AWSSDK.S3-Paket benötigt.
Verwendung von IronBarcode Zip
Wenn Sie IronBarcode ZIP verwenden, ist es wichtig, den temporären Ordner festzulegen.
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPathDim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPathDas Microsoft.ML.OnnxRuntime-Paket wird zum Lesen von Barcodes benötigt. Während das Schreiben von Barcodes auch ohne funktioniert, basiert der Standardmodus für das Lesen auf maschinellem Lernen (ML). Wenn Sie auf einen Lesemodus umschalten, der kein ML verwendet, wird das Paket nicht benötigt.
Erstellen Sie ein AWS Lambda-Projekt
Mit Visual Studio ist die Erstellung eines containerisierten AWS Lambda ein einfacher Prozess:
- Installieren Sie das AWS Toolkit für Visual Studio
- Wählen Sie ein 'AWS Lambda Project (.NET Core - C#)'
- Wählen Sie eine '.NET 8 (Container Image)' Blaupause aus und wählen dann 'Fertigstellen'.

Abhängigkeitspakete hinzufügen
Die IronBarcode-Bibliothek in .NET 8 funktioniert auf AWS Lambda ohne zusätzliche Abhängigkeiten. Um es einzurichten, aktualisieren Sie die Docker-Datei des Projekts wie folgt:
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" .
Ändern Sie den FunctionHandler-Code
Dieses Beispiel generiert einen EAN8-Barcode, lädt ihn in einen S3-Bucket hoch und liest den neu erstellten Barcode. Beim Verwenden von IronBarcode ZIP ist die Konfiguration des temporären Ordners entscheidend, da die Bibliothek Schreibberechtigungen benötigt, um den Laufzeitordner von den DLLs zu kopieren.
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 NamespaceVor dem try-Block wird das Dateiziel auf das IronBarcodeZip-Verzeichnis gesetzt, wobei der Name als global eindeutiger Bezeichner (GUID) generiert wird. Die CreateBarcode-Methode wird verwendet, um den Barcode zu erzeugen. Anschließend wird das PNG-Byte-Array an die Read-Methode übergeben, um den Barcode zu lesen. Dies zeigt, dass die AWS Lambda-Funktion in der Lage ist, Barcodes zu lesen.
Die Read-Methode akzeptiert auch ein BarcodeReaderOptions-Objekt, das Sie anpassen können, um Funktionen wie Lesen mehrerer Barcodes, Anvisieren bestimmter Bereiche, asynchrones und multithreaded Processing, Anwenden von Bildkorrekturfiltern und vieles mehr zu aktivieren.
Erhöhen Sie Speicher und Timeout
Die Menge des in der Lambda-Funktion zugewiesenen Speichers hängt von der Größe der zu verarbeitenden Dokumente und der Anzahl der gleichzeitig verarbeiteten Dokumente ab. Setzen Sie als Basislinie den Speicher auf 512 MB und das Timeout auf 300 Sekunden in aws-lambda-tools-defaults.json.
{
"function-memory-size": 512,
"function-timeout": 300
}
Wenn der Speicher nicht ausreicht, wirft das Programm den Fehler: 'Runtime exited with error: signal: killed.' Eine Erhöhung der Speichergröße kann dieses Problem lösen. Für weitere Details lesen Sie den Artikel zur Fehlerbehebung: AWS Lambda - Laufzeit beenden: Signal: Getötet.
Veröffentlichen
Um in Visual Studio zu veröffentlichen, klicken Sie mit der rechten Maustaste auf das Projekt und wählen 'Publish to AWS Lambda...', dann die erforderlichen Einstellungen konfigurieren. Mehr über das Veröffentlichen einer Lambda-Funktion können Sie auf der AWS-Website lesen.
Probieren Sie es aus!
Sie können die Lambda-Funktion entweder über die Lambda-Konsole oder über Visual Studio aktivieren.
Häufig gestellte Fragen
Wie richte ich IronBarcode auf AWS Lambda ein?
Um IronBarcode auf AWS Lambda einzurichten, müssen Sie ein AWS Lambda-Projekt in Visual Studio erstellen, erforderliche Pakete wie AWSSDK.S3 installieren, den Bereitstellungspfad für IronBarcode konfigurieren und den FunctionHandler-Code schreiben, um Barcodes in einem S3-Bucket zu lesen und zu schreiben.
Welche Pakete sind erforderlich, um IronBarcode auf AWS Lambda zu verwenden?
Sie benötigen das AWSSDK.S3-Paket zur Verwaltung von S3-Buckets und das Microsoft.ML.OnnxRuntime-Paket zum Lesen von Barcodes, vorausgesetzt, Sie verwenden den Standard-Lesemodus für maschinelles Lernen.
Wie kann ich IronBarcode in einem Dockerfile für AWS Lambda installieren?
Kopieren Sie in Ihrem Dockerfile die Build-Artefakte des .NET Lambda-Projekts in das Image und konfigurieren Sie den Bereitstellungspfad für IronBarcode für die AWS Lambda-Umgebung.
Ist ein Lizenzschlüssel für IronBarcode auf AWS Lambda erforderlich?
Ja, Sie müssen Ihren IronBarcode-Lizenzschlüssel im Code des FunctionHandler setzen, um IronBarcode innerhalb einer AWS Lambda-Funktion zu verwenden.
Welche Optionen kann ich beim Lesen von Barcodes mit IronBarcode in AWS Lambda anpassen?
Bei der Verwendung von IronBarcode in AWS Lambda können Sie Optionen anpassen wie das Lesen mehrerer Barcodes, das Anvisieren bestimmter Bildbereiche und die asynchrone Verarbeitung über das BarcodeReaderOptions-Objekt.
Wie kann ich die Konfiguration des temporären Ordners in AWS Lambda mit IronBarcode verwalten?
Stellen Sie die Konfiguration des temporären Ordners ein, indem Sie den DeploymentPath für IronBarcode in Ihrem AWS Lambda FunctionHandler auf '/tmp/' festlegen.
Was soll ich tun, wenn meine AWS Lambda-Funktion mit IronBarcode nicht mehr genügend Speicher hat?
Erhöhen Sie den zugewiesenen Speicher für Ihre Lambda-Funktion mit der Einstellung 'function-memory-size' in aws-lambda-tools-defaults.json und stellen Sie sicher, dass sie angemessen für Ihre Arbeitslast eingestellt ist.
Wie lade ich ein Barcode-Bild in einen S3-Bucket hoch, indem ich IronBarcode auf AWS Lambda verwende?
Verwenden Sie IronBarcode, um einen Barcode zu erzeugen, konvertieren Sie ihn in PNG-Binärdaten, und verwenden Sie den Amazon S3-Client, um diese Daten in Ihren angegebenen S3-Bucket hochzuladen.
Kann ich Barcodes generieren und lesen, ohne OnnxRuntime in AWS Lambda zu verwenden?
Ja, Sie können Barcodes generieren und schreiben, ohne OnnxRuntime zu verwenden, aber das Lesen erfordert OnnxRuntime, wenn Sie den Standardmodus für maschinelles Lernen verwenden. Wechseln Sie zu einem Nicht-ML-Lesemodus, wenn Sie es bevorzugen, es nicht zu verwenden.
Wie kann ich eine AWS Lambda-Funktion veröffentlichen, die IronBarcode verwendet?
Klicken Sie in Visual Studio mit der rechten Maustaste auf Ihr Projekt und wählen Sie 'Veröffentlichen auf AWS Lambda'. Konfigurieren Sie die erforderlichen Einstellungen für die Bereitstellung und folgen Sie den AWS-Richtlinien, um den Prozess abzuschließen.
Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.