Language: EN

csharp-zxing

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

ZXing.Net is an open-source C# library that allows decoding and generating barcodes or QR codes 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 barcode formats it supports 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 that we can use it on Windows, Android, and iOS.

It also 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 through the corresponding Nuget package.

Install-Package ZXing.Net

In the case of using .NET Standard or .NET 5.0 or later, we must also add the package corresponding to our architecture, for example

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

Decoding a code

Next, an example of using ZXing.Net for decoding a QR code in an image is shown:

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

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 result obtained is printed.

Encoding 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);

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 is very simple to read or write barcodes in .NET with ZXing.Net. In addition, the project’s page includes examples in WindowsForms, WPF, ASP.NET, among others.

ZXing.Net is OpenSource, and all the code and documentation is available in the project repository at https://github.com/micjahn/ZXing.Net