Generate QR code using Java Example

QR code short for Quick Response Code is a two-dimensional matrix type barcode. Initially designed for the automotive industry has gained popularity in other areas such as retail packaging, storing web address and in smart phones due to its large storage capacity compared to standard UPC barcodes and fast readability.

Unlike the old barcode that was designed to be mechanically scanned by a narrow beam of light, the QR code is detected as a 2-dimensional digital image by a semiconductor image sensor and is then digitally analyzed by a programmed processor. The processor locates the three distinctive squares at the corners of the image, and normalizes image size, orientation, and angle of viewing, with the aid of a smaller square near the fourth corner. The small dots are then converted to binary numbers and validity checked with an error-correcting code. Nowadays there are scanner apps that uses the camera to scan these QR codes in our mobile phones and tablets.

The amount of data that can be stored in the QR Code symbol depends on the datatype
Numeric only  Max. 7,089 characters (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Alphanumeric  Max. 4,296 characters (0–9, A–Z [upper-case only], space, $, %, *, +, -, ., /, :)
Binary/byte  Max. 2,953 characters (8-bit bytes) (23624 bits)
Kanji/Kana  Max. 1,817 characters
In this example we are going to learn how to generate a QR code from a String data. We take help of the open source library called ZXing((pronounced "zebra crossing") and QRGen that is built on top of Zxing library which makes it a breeze to generate the QR code in just a few lines of code. In your project you will need the following jar files
  • core.jar
  • javase.jar
  • qrgen-1.1.jar 
The core.jar and javase.jar can be found in the ZXing download, here is the link http://code.google.com/p/zxing/downloads/list and you can download qrgen-1.1.jar from here http://kenglxn.github.com/QRGen/

Generate QR code using Java

Application JSP - generateQRCode.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="robots" content="noindex,nofollow"/>
<title>Generate QR Code using QRGen and ZXing library</title>
<link rel="stylesheet" href="/resources/themes/master.css" type="text/css" />
<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />

<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript"></script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript"></script>
<script
 src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js"
 type="text/javascript"></script> 
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function() {
  
  $("#samplecode").validate({
    rules: {
     qrText: "required"
   }
  });
  
 });       
    </script> 
</head>
<body>
<div id="allContent">
<%@include file="/header.jsp"%>

<% 
String qrText =  request.getParameter("qrText");
if(qrText == null){
 qrText = "";
}
%>
<div id="myContent" style="width:50%;">
 <form id="samplecode" name="samplecode" method="POST" action="generateQRCode.jsp">
   <fieldset>
    <legend><b>&nbsp;&nbsp;&nbsp;QR Code Generator - Request&nbsp;&nbsp;&nbsp;</b></legend>

    <p>
     <label for="qrText"> Input Text for QR Code </label><br /> 
     <input id="qrText" type="text" name="qrText" size="50"
     value="<%= qrText %>"
     />
    </p>
    <input id="generate" type="submit" value="Generate QR Code" />
   </fieldset>
   <%
         if (!qrText.trim().equalsIgnoreCase("")) {
            %>
            <fieldset>
    <legend><b>&nbsp;&nbsp;&nbsp;QR Code Generator - Response&nbsp;&nbsp;&nbsp;</b></legend>
             <img src="../GenerateQRCode?qrText=<%= request.getParameter("qrText") %>">
   </fieldset>
            <%
         }
            %>
 </form>
</div> 
 
<%@include file="/footer.jsp"%>        
</div>
</body>
</html>

Source for Java Servlet - GenerateQRCode.java

package com.as400samplecode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class GenerateQRCode extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    public GenerateQRCode() {
        super();
    }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
  String qrText = request.getParameter("qrText");
  ByteArrayOutputStream out = QRCode.from(qrText).to(ImageType.PNG).withSize(300, 300).stream();
         
        response.setContentType("image/png");
        response.setContentLength(out.size());
         
        OutputStream os = response.getOutputStream();
        os.write(out.toByteArray());
        
        os.flush();
        os.close();
        
 }

}

You can choose to either create a file or ByteArrayOutputStream
File file = QRCode.from("Some input Text").file();
ByteArrayOutputStream stream = QRCode.from("Some input Text").stream();
You can change the image Type to JPG, GIF or PNG
QRCode.from("Some input Text").to(ImageType.JPG).file();
QRCode.from("Some input Text").to(ImageType.GIF).file();
QRCode.from("Some input Text").to(ImageType.PNG).file();
You can change the size the of the QR code
QRCode.from("Some input Text").withSize(200, 200).file();

Recommended Reading

References