Dynamically Generated QR Codes in ASP.Net

Taken from: http://www.acodemics.co.uk/wp-content/uploads/2013/05/visual_studio_2012_logo.png

What we want to do here is generate a QR code on pageload and show it to user in a designated div. The problem is, Image control takes an url for a source and your generated picture doesn’t have an url… yet.

This elegant solution was proposed by my good friend Istemi. Without further ado let’s dive in.

Aspx Side:


<body>
<form id="form1" runat="server">

<div id="qrcode" runat="server">

</div>

</form>
</body>

As you can see we don’t have anything special except for a curious div which has an id of qrcode and runs at server. Turns out we need this to:

Codebehind:


protected void Page_Load(object sender, EventArgs e)
{

System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
int userId = 1;
Bitmap bmp = FyeahWeb.utils.Encoder.encodeQRCode(userId.ToString());
bmp.Save(Server.MapPath(userId + ".bmp"));
img.ImageUrl = userId + ".bmp";
qrcode.Controls.Add(img);

}

As I’ve said, we need this to refer to it from codebehind and add our generated image/bitmap to the div as an Image with a source. But, you may ask, what does generate this QR code. Well, turns out we need a library to do that. I have used Zxing.net for generating my image with this code:


public static Bitmap encodeQRCode(String barcodedValue)
{

IBarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE };
Bitmap barcodeBitmap;
var result = writer.Write(barcodedValue);
barcodeBitmap = new Bitmap(result);
return barcodeBitmap;

}

Easy as pies, right?

Edit:

If you are interested in QR code in WPF and ASP.Net MVC, Scott Hanselman had written a perfect guide for that. Bonus is, you don’t even have to save the file in the server!

http://www.hanselman.com/blog/HowToDisplayAQRCodeInASPNETAndWPF.aspx

One thought on “Dynamically Generated QR Codes in ASP.Net

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>