In this article I will explain with an example, how to use dynamically
generate and display
QR Code image using
ASP.Net in C# and VB.Net.
For generating QR Codes I will make use of QRCoder which is an Open Source Library QR code generator.
QR Code Library
You will need to download the
QR code library from the following location and open the project in
Visual Studio and build it. Once it is build, you can find the DLL in the Debug folder.
Note: You can also find the QRCoder DLL in the attached sample project.
HTML Markup
The
HTML Markup consists of following control:
TextBox – For capturing barcode.
Button – For generate QR code.
PlaceHolder – generated QR code image displayed here.
<asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
<asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="btnGenerate_Click" />
<hr />
<asp:PlaceHolder ID="plBarCode" runat="server" />
Namespaces
You will need to import the following namespaces.
C#
using QRCoder;
using System.IO;
using System.Drawing;
VB.Net
Imports QRCoder
Imports System.IO
Imports System.Drawing
Generating and displaying QR code image in ASP.Net
Inside the
Button Click event handler, The Text from the
TextBox is passed to the
CreateQRCode method of the
QRCoder library which returns a Bitmap image.
Finally, saved as PNG image in MemoryStream which later is converted to a base64 string and displayed on the page using an Image control.
C#
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtCode.Text;
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
byte[]byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
plBarCode.Controls.Add(imgBarCode);
}
}
VB.Net
Protected Sub btnGenerate_Click(sender As Object, e As EventArgs)
Dim code As String = txtCode.Text
Dim qrGenerator As New QRCodeGenerator()
Dim qrCode As QRCodeGenerator.QRCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q)
Dim imgBarCode As New System.Web.UI.WebControls.Image()
imgBarCode.Height = 150
imgBarCode.Width = 150
Using bitMap As Bitmap = qrCode.GetGraphic(20)
Using ms As New MemoryStream()
bitMap.Save(ms,System.Drawing.Imaging.ImageFormat.Png)
Dim byteImage As Byte() = ms.ToArray()
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage)
End Using
plBarCode.Controls.Add(imgBarCode)
End Using
End Sub
Screenshot
Demo
Downloads