How to Generate Barcode in ASP.NET Core using C#
By FoxLearn 9/10/2024 8:47:48 AM 5.34K
After you finish creating a new ASP.NET Core project. You can create a BarcodeController by right-click on Controllers folder => Add => Controller
Selecting MVC Controller - Empty
Entering your controller name
Next, You need to install the BarcodeLib library by right-clicking on your project, then select Manage Nuget Packages => Search and Install barcodelib to your project.
Creating a ConvertImageToBytes method allows you to convert image to byte array in c#.
private byte[] ConvertImageToBytes(Image img) { using (MemoryStream ms = new MemoryStream()) { img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return ms.ToArray(); } }
Creating an Image action allows you to generate barcode in asp.net mvc core
public IActionResult Image() { Barcode barcode = new Barcode(); Image img = barcode.Encode(TYPE.UPCA, "123456789025", Color.Black, Color.White, 250, 100); var data = ConvertImageToBytes(img); return File(data, "image/jpeg"); }
If you want to embed the barcode inside html, you can right click on Index action, then create an Index view
public IActionResult Index() { return View(); }
Index View
@{ ViewData["Title"] = "Index"; } <h1>Index</h1> <img src='@Url.Action("Image")' alt="barcode" />
Press F5 to run your project, then change your url Barcode/Index
This is a basic example of how you can integrate BarcodeLib into an ASP.NET Core application to generate and serve barcodes.