BarcodeLib generates barcode images from text in .NET web applications. A minimal ASP.NET Core route encodes input and returns the resulting bytes as a JPEG response. section 3.1.2
using BarcodeLib; #1
using System.Drawing; #2
using System.Drawing.Imaging; #3
app.MapGet("/barcode/{text}", (string text) => { #4
var barcode = new Barcode(); #5
barcode.ImageFormat = ImageFormat.Jpeg; #6
_ = barcode.Encode( #7
TYPE.CODE128, #8
text, #9
Color.Black, #10
Color.White); #11
return Results.File( #12
barcode.Encoded_Image_Bytes, #13
"image/jpeg"); #14
});
This focused route creates a Barcode instance, selects JPEG output, encodes CODE128 text with foreground and background colors, and returns an image response. section 3.1.2
Account for these implementation details:
- Add BarcodeLib through the NuGet PackageReference supplied for the project. section 3.1.2
- Match the image media type to the selected ImageFormat, such as image/jpeg for JPEG output. section 3.1.2
- Validate input because barcode types differ in their accepted values; some accept only numbers. section 3.1.2
- Use BarcodeLib version 2.4.0 when following this API; version 3 introduces breaking changes. section 3.1.2
