Windows Forms: How to Create Barcode Images from a string in C#

This post shows you How to Create Barcode Images from a string using the BarcodeLib in C# Windows Forms Application.

If you want to generate one dimensional barcodes, you can use the BarcodeLib to create different types of barcodes in c#. The barcodelib is an open source library that provides an easy class for developers to use when they need to create barcode images from a string of data.

Creating Barcode Images in C#

For example: UPC-A, CODE 128, CODE 11, ISBN, ITF14, EAN13

To create barcode image c# you can design a simple ui as shown below.

Create barcode image C#

Next, You need to install the Barcodelib to your project by right-clicking on your project, then select Manage Nuget Packages... ->search 'barcodelib'->install it.

After installing the barcodelib, you can add the click event handler to the Generate button that allows you to create barcode image in c#.

private void btnGenerate_Click(object sender, EventArgs e)
{
    Barcode barcode = new Barcode();
    Color foreColor = Color.Black;
    Color backColor = Color.Transparent;
    Image image = barcode.Encode(TYPE.UPCA, txtBarcode.Text, foreColor, backColor, (int)(picBarcode.Width * 0.8), (int)(picBarcode.Height * 0.8));
    picBarcode.Image = image;    
}

You can create a barcode image with the width*80% and height*80% of PictureBox size.

UPC-A: You should enter 11 or 12 number

For example to encode "027010346149"

barcode upc-a

If you want to save the barcode to an image file you can write your code as shown below.

string fileName = Application.StartupPath + "\\upca.png";
barcode.Save(fileName, ImageFormat.Png);

You can also use the SaveFileDialog to enter your barcode image name and save it to your disk.

using(SaveFileDialog sfd = new SaveFileDialog() { Filter = "PNG|*.png"})
{
     if(sfd.ShowDialog() == DialogResult.OK)
          image.Save(sfd.FileName, ImageFormat.Png);
}

CODE128

You only need to change TYPE.UPCA to TYPE.CODE128

barcode 128a

For example to encode "12345678".

CODE 11

Change the barcode type to TYPE.CODE11

bar code11

For example to encode "123-4610"

ISBN

Change the barcode type to TYPE.ISBN

barcode isbn

For example to encode "9782181474100"

ITF14

Change the barcode type to TYPE.ITF14

barcode ITF14

For example to encode "13352056870252"

EAN13

Change the barcode type to TYPE.EAN13

barcode EAN13

For example to encode "965120147762"

Through this c# example above, I showed you how to use the free open source barcodelib to generate multiple types of barcodes. Such as, UPC-A, CODE 128, CODE 11, ISBN, ITF14, EAN13.