csharp-zxing

How to create QR and barcodes in C# with ZXing.Net

  • 3 min

ZXing.Net is an open-source C# library that enables barcode or QR code decoding and generation in .NET applications.

It is an implementation of the popular ZXing (“zebra crossing”) library developed in Java, which has been ported to C# for use in .NET applications.

ZXing.Net is capable of decoding different types of barcodes. Some of the supported barcode formats are:

1D product1D industrial2D
UPC-ACode 39QR Code
UPC-ECode 93Data Matrix
EAN-8Code 128Aztec
EAN-13CodabarPDF 417
UPC/EAN Extension 2/5ITFMaxiCode
RSS-14
RSS-Expanded

It is cross-platform, compatible with .NET Framework, .NET Standard, .NET Core, Unity. This means we can use it on Windows, Android, and iOS.

Furthermore, it has ‘bindings’ to be used in combination with other libraries, such as System.Drawings, ImageSharp, OpenCVSharp, SkiaSharp, EmguVB, among others.

How to Use ZXing.Net

We can easily add the library to a .NET project via the corresponding Nuget package.

Install-Package ZXing.Net

If using .NET Standard or .NET 5.0 or later, we also need to add the package corresponding to our architecture, for example:

Install-Package ZXing.Net.Bindings.Windows.Compatibility

Decode a Code

The following is an example of using ZXing.Net to decode a QR code in an image:

using ZXing;

// Load the image containing the QR code
var bitmap = new Bitmap("path_to_your_image.png");

// Decoding the barcode
var reader = new BarcodeReader();
var result = reader.Decode(bitmap);

// Printing the result
if (result != null)
{
    Console.WriteLine("QR code content: " + result.Text);
}
else
{
    Console.WriteLine("QR code could not be decoded");
}

Copied!

In this example, an image containing a QR code is loaded and a barcode reader object is created. Then, the barcode is decoded and the obtained result is printed.

Encode a Barcode

To generate, for example, a QR code with Zxing.Net, we can use the following code to generate a barcode:

using ZXing;

var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options.Width = 200;
barcodeWriter.Options.Height = 200;

var barcodeBitmap = barcodeWriter.Write("This is a test barcode.");
barcodeBitmap.Save("path_to_your_file.png", ImageFormat.Png);

Copied!

Where we can configure the type of code to generate (QR code, barcode, etc.), width, height, background color… among many other options.

As we can see, it’s very simple to read or write barcodes in .NET with ZXing.Net. Additionally, the project’s page includes examples for WindowsForms, WPF, ASP.NET, among others.