ASP.NET Core: Generate Barcode using ASP.NET Core in C#

This post shows you How to Generate BarCode using ASP.NET Core in C#

After you finish creating a new ASP.NET Core project. You can create a BarcodeController by right-click on Controllers folder => Add => Controller

create a controller in coreSelecting MVC Controller - Empty

add empty mvc controller

Entering your controller name

Next, Right-click on your project, then select Manage Nuget Packages => Search and Install barcodelib to your project.

barcodelib c#

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 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";


<img src='@Url.Action("Image")' alt="barcode" />

Press F5 to run your project, then change your url Barcode/Index