Dynamically Generating QR Codes In C#

Introduction

QR stands for Quick Response; it’s a type of two-dimensional barcode that is used to store small amounts of text or data. It was created by the Japanese corporation Denso-Wave and aims to decode contents at high speed. Nowadays, QR Codes are used in mobile phones that can use the contents of QR Codes as a URL to open in the phone’s Web browser. By using QR Codes, a developer can encode content into a QR Code image that can be saved in JPEG, GIF, PNG, or Bitmap formats. Also, by using the reverse technique, the QR decoder can decode a QR Code image. To scan a QR Code, you need to have a scanner app on your smartphone that can scan QR code.

In this article, I will briefly describe and demonstrate the functionalities of the QR Code library that works with ASP.NET MVC applications.

Advantages of QR Codes

The main advantage of QR Codes is their versatility. QR Codes can be a great response mechanism for mobile users. QR Codes are easily trackable. By using analytics and unique codes, marketers can gain some valuable information about how well campaigns are doing. QR Codes can be cost effective because you don’t have to pay anything when creating the QR code. QR Codes are error free. The only way to connect consumers to online content is by using a URL. But, typing a URL is time-consuming and inconvenient on a mobile screen. Consumers are also likely to make errors when typing. Scanning a QR Code that opens an URL is much faster and error-free process.

Generating QR Codes by Using the ZXing.Net Library

ZXing.Net is an open source library. It was originally created for Java applications for creating multi-format 1D/2D barcode images. The latest version of ZXing.Net is also compatible with .NET 2.0, .NET 3.5, .NET 4.0, .NET 4.5, .NET 4.6 and the .NET 4.7 Frameworks.

In the following ASP .NET application, I will be using the “ZXing.Net” library to generate a QR Code and read data from that image. If you find yourself struggling as you work along, consider visiting the TechRepublic Academy for dozens of high-quality C# classes.

Step 1

Create a new ASP.NET Web Application from Visual Studio. Add the “ZXing.Net” NuGet library in our application. To add ZXing.Net, right-click your application -> Select Manage NuGet Packages -> Go to Browse Tab -> Search for ZXing.Net ->. From the list, select ZXing.Net and install it. Refer to Figure 1, that shows how to install the component.

Installing the ZXing.NET NuGet package
Figure 1: Installing the ZXing.Net NuGet package

Step 2

Once you install the ZXing.Net package in your application, next add an ASPX page named QCCode.aspx in your project (see Figure 2).

Adding the ASPX page in the Project
Figure 2: Adding the ASPX page in the Project

Open your ASPX page and write the code given in the following code snippet.

<%@ Page Language="C#" AutoEventWireup="true"
   CodeBehind="QCCode.aspx.cs"
   Inherits="QRCodeSample.QCCode" %>
<!DOCTYPE html>
<html >
   <head runat="server">
      <title>Sample ASP.NET application to Generate and
         Read QR Code from a Browser</title>
   </head>
   <body>
      <form id="QCFrom" runat="server">
         <div>
            <asp:TextBox ID="txtQCCode" runat="server">
            </asp:TextBox>
            <asp:Button ID="btnQCGenerate" runat="server"
               Text="Create My QR Code"
               OnClick="btnQCGenerate_Click" />
            <hr/>
            <asp:Image ID="imgageQRCode" Width="100px"
               Height="100px" runat="server"
               Visible="false" /> <br /><br />
            <asp:Button ID="btnQCRead" Text="Read My QR Code"
               runat="server" OnClick="btnQCRead_Click" />
               <br /><br />
            <asp:Label ID="lblQRCode" runat="server">
            </asp:Label>
         </div>
      </form>
   </body>
   </html>

Step 3

Now, open the code behind file QCCode.Aspx.cs; copy and paste the code mentioned in the following snippet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using ZXing;


namespace QRCodeSample
{
   public partial class QCCode : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {

      }
      // Event to generate the QC Code
      protected void btnGenerate_Click(object sender, EventArgs e)
      {
         GenerateMyQCCode(txtQCCode.Text);
      }
      protected void btnRead_Click(object sender, EventArgs e)
      {
         ReadQRCode();
      }
      private void GenerateMyQCCode(string QCText)
      {
         var QCwriter = new BarcodeWriter();
         QCwriter.Format = BarcodeFormat.QR_CODE;
         var result = QCwriter.Write(QCText);
         string path = Server.MapPath("~/images/MyQRImage.jpg");
         var barcodeBitmap = new Bitmap(result);

         using (MemoryStream memory = new MemoryStream())
         {
            using (FileStream fs = new FileStream(path,
               FileMode.Create, FileAccess.ReadWrite))
            {
               barcodeBitmap.Save(memory, ImageFormat.Jpeg);
               byte[] bytes = memory.ToArray();
               fs.Write(bytes, 0, bytes.Length);
            }
         }
         imgageQRCode.Visible = true;
         imgageQRCode.ImageUrl = "~/images/MyQRImage.jpg";

      }

      private void ReadQRCode()
      {
         var QCreader = new BarcodeReader();
         string QCfilename = Path.Combine(Request.MapPath
            ("~/images"), "MyQRImage.jpg");
         var QCresult = QCreader.Decode(new Bitmap(QCfilename));
         if (QCresult != null)
         {
            lblQRCode.Text = "My QR Code: " + QCresult.Text;
         }
      }
   }
}

In the preceding code, I have added a reference of the ZXing namespace to generate and read QR Codes in our Web applications.

Now, run the application. You will get a result as shown in Figure 3.

Output of the execution
Figure 3: Output of the execution

Conclusion

Thanks for reading the article. I hope it helped you to search for an easy solution to create QR Codes in .NET.

That’s all for today. Happy reading!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read