(Print this page)

Generate and consume QR codes in .Net applications
Published date: Wednesday, September 19, 2018
On: Moer and Éric Moreau's web site

I hope by now you all now what a Quick Response (long version for QR) code is. If not, or if you want to see if there is something about QR codes you don’t know, Wikipedia as quite some good details on that. You can also point your browser to the inventor of the QR code Denso Wave.

This article will show you how to encode (create) a QR code as well as to decode (consume) one from a .Net application.

The downloadable code

This month’s downloadable demo solution contains both VB and C# projects. The solution was created using Visual Studio 2017 but should also work in most older versions as well.

The projects of this solution will use the free ZXing.Net library. As per the library NuGet page, the library is compatible with everything .Net even including SilverLight and Windows Phone if you still have interest in those platforms!

Creating the demo project

For the demo purpose, I am just creating here a very simple solution containing both VB and C# Windows Forms project. Nothing fancy, as usual.

As shown on Figure 1, the form shows these simple controls:

  • A textbox (txtInput) to let you enter a value.
  • A PictureBox (picResult) to display the generated QR Code (or the image loaded from the Load button).
  • A Save button (btnSaveQRCode).
  • A Load button (btnLoadQRCode).

Figure 1: The demo application in action

Adding the library

The easiest way to add the required library to your project is to use the NuGet package. Just search for ZXing.Net by Michael Jahn. Notice that it has 780K downloads, not bad!

Figure 2: Adding ZXing.Net NuGet package

Before I forget, it is worth mentioning that this library does not only create/consume QR codes but also many different kinds of barcodes (if you need them).

Encoding a QR code

For the demo, I will do something really simple. I will let you enter some text in the textbox control and I will use the library to generate the QR code on the fly because it is so quick. You will be able to see the resulting image in a PictureBox.

To achieve that, you will need to handle the TextChanged event of the textbox with code like this:

Private Sub txtInput_TextChanged(sender As Object, e As EventArgs) Handles txtInput.TextChanged
    If String.IsNullOrWhiteSpace(txtInput.Text) Then
        picResult.Image = Nothing
        Return
    End If

    Dim options As EncodingOptions = New QrCodeEncodingOptions With {
            .Width = picResult.Width,
            .Height = picResult.Height
            }
    Dim objWriter As BarcodeWriter = New BarcodeWriter With {
            .Format = BarcodeFormat.QR_CODE,
            .Options = options
            }
    picResult.Image = New Bitmap(objWriter.Write(txtInput.Text))
End Sub
private void TxtInput_TextChanged(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(txtInput.Text))
    {
        picResult.Image = null;
        return;
    }

    EncodingOptions options = new QrCodeEncodingOptions
    {
        Width = picResult.Width,
        Height = picResult.Height
    };
    BarcodeWriter objWriter = new BarcodeWriter
    {
        Format = BarcodeFormat.QR_CODE,
        Options = options
    };
    picResult.Image = new Bitmap(objWriter.Write(txtInput.Text));
}

If you look closely to this short snippet of code, it does really simple things:

  • It ensures that there is some text to encode (otherwise an exception is thrown).
  • It creates some encoding options to specify the width and the height of the QR code to generate.
  • It creates an instance of a BarcodeWriter object specifying to create a QR_Code format and passing the options.
  • It finally calls the Write method of the object and sends the resulting image to the PictureBox control.

It can’t be simpler!

And because you might want to save the generated QR code as a file (to later test the decoding!), I have added a save button to my test form. I use the Save method of the PictureBox control to save the image to the current folder.

Private Sub btnSaveQRCode_Click(sender As Object, e As EventArgs) Handles btnSaveQRCode.Click
    Dim strFileName As String = IO.Path.Combine(Application.StartupPath, "demo.jpg")
    picResult.Image.Save(strFileName, ImageFormat.Jpeg)
    MessageBox.Show("Demo.jpg has been saved")
End Sub
private void btnSaveQRCode_Click(object sender, EventArgs e)
{
    string strFileName = System.IO.Path.Combine(Application.StartupPath, "demo.jpg");
    picResult.Image.Save(strFileName, ImageFormat.Jpeg);
    MessageBox.Show("Demo.jpg has been saved");
}

Decoding a QR Code

This library is not only good at creating a QR code for some text you want, it can also decode an image containing a QR code back to text.

The code is not much more complex. As you can see here, I first load the image into PictureBox control

Private Sub btnLoadQRCode_Click(sender As Object, e As EventArgs) Handles btnLoadQRCode.Click
    Dim strFileName As String = IO.Path.Combine(Application.StartupPath, "demo.jpg")

    If Not IO.File.Exists(strFileName) Then
        MessageBox.Show("File demo.jpg does not exist!")
        Return
    End If

    picResult.Image = Nothing
    Dim bmpImage As Bitmap = New Bitmap(strFileName)
    picResult.Image = bmpImage

    Dim objReader As BarcodeReader = New BarcodeReader()
    Dim objResult As Result = objReader.Decode(bmpImage)
    If objResult IsNot Nothing Then
        MessageBox.Show("The QR code = " + objResult.Text)
    Else
        MessageBox.Show("Cannot decipher this image!")
    End If
End Sub
private void btnLoadQRCode_Click(object sender, EventArgs e)
{
    string strFileName = System.IO.Path.Combine(Application.StartupPath, "demo.jpg");
    if (!System.IO.File.Exists(strFileName))
    {
        MessageBox.Show("File demo.jpg does not exist!");
        return;
    }

    picResult.Image = null;
    Bitmap bmpImage = new Bitmap(strFileName);
    picResult.Image = bmpImage;

    BarcodeReader objReader = new BarcodeReader();
    Result objResult = objReader.Decode(bmpImage);
    if (objResult != null)
        MessageBox.Show("The QR code = " + objResult.Text);
    else
    {
        MessageBox.Show("Cannot decipher this image!");
    }
}

You can even try to foul the library by passing an image that is not QR Code (or any recognized barcode), the Decode method just return a null value.

Conclusion

QR codes are the new barcodes. But a lot better. And now that our phones directly support them, it just become something everybody get accustomed to. QR codes are everywhere and now maybe even more now that you also know how easy they be created (and consumed).


(Print this page)