Create QR Codes With Google Web APIs

Introduction

This article explains a simple method to create a QR Code inside a standard control. The solution is a UserControl for future re-usability. There are many libraries that could help us in operations like that, but in this article I will use Google Charts () together with System.Net and System.IO namespaces.

Google Charts can be queried using POST request (see the details here). Therefore, we must:

a) query the remote server, with specific POST parameters (more on this later),
b) retrieve the server's response (a PNG image)
c) use it for our means, namely paint it on our control.

Creating UserControl

Open a new project in Visual Studio, then add a new User Control. I've set the BorderStyle property to Fixed3D and DoubleBuffered to True (to avoid flickering when the control refreshes itself).

 

The standard URL through that we will query is the following: http://chart.googleapis.com/chart?chs={WIDTH}x{HEIGHT}&cht=qr&chl={DATA} (parameters in brackets will be replaced with real parameters). chs will specify QR Code resolution (width x height), whereas chl will contain the data to be represented using the barcode. The parameter related to the barcode size could be easily deduced from our control's property (since a standard control has a width and a height), but we will create a new property to store a certain amount of text, representing the data that our QR Code will show.

In our UserControl, we start declaring the standard URI as a constant, our Data Property and an internal variable to store data in the local context:

  1.     Const _GOOGLE_URL As String = "http://chart.googleapis.com/chart?chs={WIDTH}x{HEIGHT}&cht=qr&chl={DATA}"  
  2.     Dim _DATA As String = String.Empty  
  3.    
  4.     Property Data As String  
  5.         Get  
  6.             Return _DATA  
  7.         End Get  
  8.         Set(value As String)  
  9.             _DATA = value  
  10.         End Set  
  11.     End Property  
When we use our Control the Data Property will be available in both Code View and Design Mode:
 
 
 
Now that we can compose a URI with all the requested parameters, we must forge a Data Property to encode its content before the web request. This way, we can be sure that no special character will come to break our query. I've implemented a private function for this that, after calling, will return the URI with modified parameters, the least of which will be encoded (thanks to the WebUtility.UrlEncode function).
  1. Private Function getQRURI() As String  
  2.     Dim _qrAddr As String = _GOOGLE_URL.Replace("{WIDTH}"Me.Width.ToString).Replace("{HEIGHT}"Me.Height.ToString)  
  3.     _qrAddr = _qrAddr.Replace("{DATA}", WebUtility.UrlEncode(_DATA))  
  4.    
  5.     Return _qrAddr  
  6. End Function  

We'll replace the first two tag parameters, {WIDTH} and {HEIGHT}, with our control's size, whereas the data's parameter will be the content of our Data Property, encoded (for details on WebUtility.UrlEncode, please refer here).

We're now ready to fetch our image from remote servers and use the returning buffer to paint our QR Code on our control. Since I want a QR Code to be painted at the standard OnPaint Event (taking advantage of the PaintEventArgs argument it exposes), I will override it, adding my code as in the following:

  1. Protected Overrides Sub OnPaint(e As PaintEventArgs)  
  2.     MyBase.OnPaint(e)  
  3.     If _DATA Is Nothing Then Exit Sub  
  4.    
  5.     Dim client As New WebClient()  
  6.     Dim bytes() As Byte = client.DownloadData(getQRURI())  
  7.     client.Dispose()  
  8.    
  9.     Dim memStream As New IO.MemoryStream(bytes)  
  10.     Dim bmp As Bitmap = Bitmap.FromStream(memStream)  
  11.     memStream.Dispose()  
  12.    
  13.     e.Graphics.DrawImage(bmp, 0, 0)  
  14. End Sub  

MyBase.OnPaints calls standard paint operations. Next, we will check if there is data to query (exiting method otherwise), and proceeding the querying remote server with a new instance of WebClient. Using the call at DownloadData, to which we pass the result of our URI-formatting function, we'll fill an array of bytes that is the server response, in other words the PNG image representing our QR Code. 

An image-type variable can be initialized by reading a Stream (like when we wish to open an image existing on our hard-drive, a stream to our local copy of it). Since we'll have our bytes in memory, we can declare a MemoryStream based on our array and use it as a Bitmap source. At this point, having a perfectly working bitmap, we can exploit the variable e that the OnPaint event provides access to us, to draw the image on our control, at [0;0] location.

Use QrBox in Windows Forms

After compiling our project, the QRBox will be available in the ToolBox, ready to be used on our Forms. 
 
 

Using it is simple and sufficient to set the Data Property and call for a control's refresh.

The following example Form shows how it works: I've added a QrBox control to my Form together with a standard TextBox and Button.

 
When the user presses the "Make" Button, we'll read the TextBox content, passing it to the QrBox Data Property and invoking the Refresh() method. This is done to start the remote query towards Google Charts. The code on the Button click is shown below.
  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
  2.     QrBox1.Data = TextBox1.Text  
  3.     QrBox1.Refresh()  
  4. End Sub  
The code for QrBox UserControl is as follows:
  1. Imports System.Net  
  2.    
  3. Public Class QRBox  
  4.     Const _GOOGLE_URL As String = "http://chart.googleapis.com/chart?chs={WIDTH}x{HEIGHT}&cht=qr&chl={DATA}"  
  5.     Dim _DATA As String = String.Empty  
  6.    
  7.     Property Data As String  
  8.         Get  
  9.             Return _DATA  
  10.         End Get  
  11.         Set(value As String)  
  12.             _DATA = value  
  13.         End Set  
  14.     End Property  
  15.    
  16.     Private Function getQRURI() As String  
  17.         Dim _qrAddr As String = _GOOGLE_URL.Replace("{WIDTH}"Me.Width.ToString).Replace("{HEIGHT}"Me.Height.ToString)  
  18.         _qrAddr = _qrAddr.Replace("{DATA}", WebUtility.UrlEncode(_DATA))  
  19.    
  20.         Return _qrAddr  
  21.     End Function  
  22.    
  23.     Protected Overrides Sub OnPaint(e As PaintEventArgs)  
  24.         MyBase.OnPaint(e)  
  25.         If _DATA Is Nothing Then Exit Sub  
  26.    
  27.         Dim client As New WebClient()  
  28.         Dim bytes() As Byte = client.DownloadData(getQRURI())  
  29.         client.Dispose()  
  30.    
  31.         Dim memStream As New IO.MemoryStream(bytes)  
  32.         Dim bmp As Bitmap = Bitmap.FromStream(memStream)  
  33.         memStream.Dispose()  
  34.    
  35.         e.Graphics.DrawImage(bmp, 0, 0)  
  36.     End Sub  
  37.    
  38.     Public Sub New()  
  39.         InitializeComponent()  
  40.     End Sub  
  41. End Class  

Demo

The code discussed in the article could be downloaded from here.

I hope this will be useful for your projects.


Similar Articles