DEV Community

IronSoftware
IronSoftware

Posted on • Originally published at ironsoftware.com

C# QR Code Generator for .NET

As you may have read in the Creating a Barcode introductory tutorial, creating, styling, and exporting barcodes as images with Iron Barcode is incredibly simple and may often be achieved in a single line of code.

In this example, we will look more in depth at QR codes, which are becoming increasingly popular in industrial applications and also in retail.

How to Read and Generate QR Codes in C#: Follow these 5 Steps

  1. Download QR code Generator Library
  2. Create a QR code by adding one line of code
  3. Add your logo to a QR code
  4. Verify your QR code is Readable
  5. Verify your QR code is Readable

Install QR Code Generator Library in C

Before we start we need to install the BarCode NuGet Package.

PM > Install-Package Barcode

https://www.nuget.org/packages/BarCode/

As an alternative, the IronBarCode DLL can be downloaded and added to your project as a reference from [.NET Barcode DLL].

Importing NameSpaces

For this tutorial we need to make sure our class files reference IronBarCode and also some normal system assemblies.

using IronBarCode;
using System;
using System.Drawing;
using System.Linq;
Enter fullscreen mode Exit fullscreen mode

Create a QR Code with 1 Line of Code

Our first example shows us how to create a standardized barcode with some simple text, a 500 pixel square diameter, with a medium error correction.

C#:

// Generate a Simple BarCode image and save as PDF
QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium).SaveAsPng("MyQR.png");
Enter fullscreen mode Exit fullscreen mode

VB:

' Generate a Simple BarCode image and save as PDF
QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium).SaveAsPng("MyQR.png")
Enter fullscreen mode Exit fullscreen mode

Error correction allows us to define how easy it will be for a QR code to be read in real world circumstances. Higher error correction levels create larger QR codes with more pixels and more complexity.

Adding a Logo

In the second example, we will look at a use case where a company wishes to add to a logo to their QR code, which is something we see commonly these days. By using the QRCodeWriter.CreateQRCodeWithLogo method, in the code sample below you can see how easy this is.

C#:

// Adding a Logo
var MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500);
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen);
Enter fullscreen mode Exit fullscreen mode

VB:

' Adding a Logo
Dim MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500)
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen)
Enter fullscreen mode Exit fullscreen mode

This example adds the Visual Studio logo to the barcode. It automatically sizes it to an appropriate size where the pure code is still readable and aligns that logo to the QR code square grid, so that it looks appropriate. The next line of code colors the barcode dark green. However, it does not discolor the logo.

Save as Image PDF or HTML

Finally, we save that QR as a PDF. The final line of code opens the PDF in your default PDF browser for your convenience.

C#:

// Adding a Logo
var MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500);
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen);
//Save as PDF
MyQRWithLogo.SaveAsPdf("MyQRWithLogo.pdf");
//Also Save as HTML
MyQRWithLogo.SaveAsHtmlFile("MyQRWithLogo.html");
Enter fullscreen mode Exit fullscreen mode

VB:

' Adding a Logo
Dim MyQRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 500)
MyQRWithLogo.ChangeBarCodeColor(System.Drawing.Color.DarkGreen)
'Save as PDF
MyQRWithLogo.SaveAsPdf("MyQRWithLogo.pdf")
'Also Save as HTML
MyQRWithLogo.SaveAsHtmlFile("MyQRWithLogo.html")
Enter fullscreen mode Exit fullscreen mode

Verifying QR Codes

When adding logos to QR codes and changing colors, we want to make sure that our QR is still readable.

By using the GeneratedBarcode.Verify() method, we can test whether or not our barcode is still readable.

In the following code example, we will see that changing a QR code to light blue actually makes it unreadable. We detect this within the code and prefer dark blue.

C#:

// Verifying QR Codes
// using System.Drawing;
var MyVerifiedQR = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 350);
MyVerifiedQR.ChangeBarCodeColor(Color.LightBlue);
if (!MyVerifiedQR.Verify())
{
    Console.WriteLine("\t LightBlue is not dark enough to be read accurately.  Lets try DarkBlue");
    MyVerifiedQR.ChangeBarCodeColor(Color.DarkBlue);
}
MyVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html");
// open the barcode htm, file in your default web browser
System.Diagnostics.Process.Start("MyVerifiedQR.html");
Enter fullscreen mode Exit fullscreen mode

VB:

Imports Microsoft.VisualBasic
' Verifying QR Codes
' using System.Drawing;
Dim MyVerifiedQR = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/csharp/barcode/", "visual-studio-logo.png", 350)
MyVerifiedQR.ChangeBarCodeColor(Color.LightBlue)
If Not MyVerifiedQR.Verify() Then
    Console.WriteLine(vbTab & " LightBlue is not dark enough to be read accurately.  Lets try DarkBlue")
    MyVerifiedQR.ChangeBarCodeColor(Color.DarkBlue)
End If
MyVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html")
' open the barcode htm, file in your default web browser
System.Diagnostics.Process.Start("MyVerifiedQR.html")
Enter fullscreen mode Exit fullscreen mode

The final lines of code export the QR code as a standalone HTML file with no assets and then open that HTML file in your default browser.

Reading and Writing Binary Data

QR codes are an excellent format for dealing with binary data. Sometimes binary data is simply more space-efficient or more appropriate than dealing with text.

In this example, we will encode some binary data from a string, write that to a barcode in QR format, and then read that back as a bit array of binary data. You will note that this feature is not common to many barcode libraries, making Iron Barcode unique in this capacity.

C#:

// Reading and Writing Binary Data
// using System.Linq;
//Create Some Binary Data - This example equally well for Byte[] and System.IO.Stream
byte[] BinaryData = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/");
//WRITE QR with Binary Content
QRCodeWriter.CreateQrCode(BinaryData, 500).SaveAsImage("MyBinaryQR.png");
//READ QR with Binary Content
var MyReturnedData = BarcodeReader.QuicklyReadOneBarcode("MyBinaryQR.png");
if (BinaryData.SequenceEqual(MyReturnedData.BinaryValue))
{
    Console.WriteLine("\t Binary Data Read and Written Perfectly");
}
else
{
    throw new Exception("Corrupted Data");
}
Enter fullscreen mode Exit fullscreen mode

VB:

Imports Microsoft.VisualBasic
' Reading and Writing Binary Data
' using System.Linq;
'Create Some Binary Data - This example equally well for Byte[] and System.IO.Stream
Dim BinaryData() As Byte = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/")
'WRITE QR with Binary Content
QRCodeWriter.CreateQrCode(BinaryData, 500).SaveAsImage("MyBinaryQR.png")
'READ QR with Binary Content
Dim MyReturnedData = BarcodeReader.QuicklyReadOneBarcode("MyBinaryQR.png")
If BinaryData.SequenceEqual(MyReturnedData.BinaryValue) Then
    Console.WriteLine(vbTab & " Binary Data Read and Written Perfectly")
Else
    Throw New Exception("Corrupted Data")
End If
Enter fullscreen mode Exit fullscreen mode

Image description

In summary, the Barcode C# Library is specifically designed with real world QR code usage in mind. Not only does it read QR codes quickly and accurately, but it allows us to style them, add logos, verify barcodes, and encode them with binary data.

Reading QR Codes

To save you jumping between tutorials I will add a code sample for my favorite way to read QR codes using Iron BarCode.

C#:

using IronBarCode;
using System;
using System.Drawing;
//...
BarcodeResult Result = BarcodeReader.QuicklyReadOneBarcode("QR.png", BarcodeEncoding.QRCode);
if (Result != null)
{
    Console.WriteLine(QRResult.Value);
}
Enter fullscreen mode Exit fullscreen mode

VB:

Imports IronBarCode
Imports System
Imports System.Drawing
'...
Private Result As BarcodeResult = BarcodeReader.QuicklyReadOneBarcode("QR.png", BarcodeEncoding.QRCode)
If Result IsNot Nothing Then
    Console.WriteLine(QRResult.Value)
End If
Enter fullscreen mode Exit fullscreen mode

A more advanced form also exists with more developer control:

C#:

using IronBarCode;
using System;
using System.Drawing;
//...
BarcodeResult Result = BarcodeReader.ReadASingleBarcode("QR.png",  BarcodeEncoding.QRCode, BarcodeReader.BarcodeRotationCorrection.Low, BarcodeReader.BarcodeImageCorrection.None);
if (Result != null)
{
    Console.WriteLine(QRResult.Value);
}
Enter fullscreen mode Exit fullscreen mode

VB:

Imports IronBarCode
Imports System
Imports System.Drawing
'...
Private Result As BarcodeResult = BarcodeReader.ReadASingleBarcode("QR.png", BarcodeEncoding.QRCode, BarcodeReader.BarcodeRotationCorrection.Low, BarcodeReader.BarcodeImageCorrection.None)
If Result IsNot Nothing Then
    Console.WriteLine(QRResult.Value)
End If
Enter fullscreen mode Exit fullscreen mode

Moving Forward

To learn more about this example and working with QR does in C#, we encourage you to fork it on out GitHub page or download the source code from our site.

Source Code Downloads

Download this C# QR Code Generator Tutorial and DLL

  • Github Repository
  • Source Code Zip

Further Documentation

You may also find the QRCodeWriter and BarcodeReader classes within the API Reference of interest.

They document the full feature set of Iron Barcode, a VB .NET Barcode Generator, which could not possibly be packed into a single tutorial


Top comments (0)