Thanks to smartphones, QR codes are becoming more and more mainstream and they are becoming more and more useful. From bus shelters, product packaging, home improvement stores, cars to many websites, they all integrate QR codes on their web pages to allow people to find them quickly. With the growing number of smartphone users, the use of QR codes is rising exponentially.
Let’s take a look at a brief overview of QR codes and how to generate them in Java.
Introduction to QR code
QR code (Quick Response code) is a type of matrix barcode (or QR code), which was first designed for the automotive industry. Thanks to their fast readability and large storage capacity, QR codes are becoming popular outside the automotive industry. The pattern consists of black squares arranged in an orderly manner on a white background. The encoded data can be one of four standard data (numeric, alphanumeric, byte/binary, Chinese characters), but can also be extended to implement more data.
Toyota subsidiary Denso Wave invented the QR code in 1994 to track vehicles on the production line. Since then, QR codes have become the most popular literal translation of 2D barcodes. QR codes are designed to support high-speed decoding of content.
Hello World implementing QR code in Java
Zebra Crossing (ZXing) is a great tool that can be used to generate and parse QR codes on almost all platforms (Android, JavaSE, iPhone, RIM, Symbian) Open source library. However, if you just want to generate a simple QR code, it is not easy to use it.
QRGen is developed on the basis of ZXing. This library makes generating QR codes using Java a piece of cake. It depends on ZXing, so when generating patterns, you need the jar packages of both ZXing and QRGen.
You will not find the jar file on the ZXing download page. You have to compile it yourself from the source code. I will generate it for you. The link is here.
zxing-core-1.7.jar (346 KB)
zxing-javase-1.7.jar (21 KB)
QRGen’s jar package can be downloaded from the official website.
Import them into the classpath and then execute the following Java code:
package net.viralpatel.qrcode; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import net.glxn.qrgen.QRCode; import net.glxn.qrgen.image.ImageType; public class Main { public static void main(String[] args) { ByteArrayOutputStream out = QRCode.from("Hello World").to(ImageType.PNG).stream(); try { FileOutputStream fout = new FileOutputStream(new File( "C:QR_Code.JPG")); fout.write(out.toByteArray()); fout.flush(); fout.close(); } catch (FileNotFoundException e) { // Do Logging } catch (IOException e) { // Do Logging } } }
These codes are very intuitive. We use the QRCode class to generate the QR code stream and write it to the file C:QR_Code.jpg through the byte stream.
QR_Code_Java.zip (339 KB)
If you open this JPEG file and scan it with your iPhone or Android QR code tool, you will see a cool "Hello World"
Except using QRGen API to generate data streams, we can also use the following API to create QR codes:
// get QR file from text using defaults File file = QRCode.from("Hello World").file(); // get QR stream from text using defaults ByteArrayOutputStream stream = QRCode.from("Hello World").stream(); // override the image type to be JPG QRCode.from("Hello World").to(ImageType.JPG).file(); QRCode.from("Hello World").to(ImageType.JPG).stream(); // override image size to be 250x250 QRCode.from("Hello World").withSize(250, 250).file(); QRCode.from("Hello World").withSize(250, 250).stream(); // override size and image type QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file(); QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();
Generate QR codes for website links (URL) in Java
The most common application of QR codes is to create a specific URL for a website Web or download pages bring traffic. As such, QR codes often encode a URL or website address that users can scan with their phone's camera and open in their browser. URLs can be encoded directly in QR codes. In the Hello World example above, just replace the string "Hello World" with the URL that needs to be encoded. Here is the code snippet:
ByteArrayOutputStream out = QRCode.from("http://viralpatel.net").to(ImageType.PNG).stream();
QR code in Servlet
Most of the time, you need to dynamically generate some QR codes on the website. We have seen how easy it is to generate QR codes in Java. Now, let's see how to integrate generating QR codes into Java Servlet.
The following is a simple HTTP Servlet using QRGen and ZXing libraries to create QR codes. The content of the QR code can be provided by the user.
The index.jsp file contains a simple HTML form with input boxes and a submit button. The user can enter the text he wishes to encode and submit it.
index.jsp
<form action="qrservlet" method="get"> <p>Enter Text to create QR Code</p> <input name="qrtext" type="text"> <input value="Generate QR Code" type="submit"> </form>
The secret is in QRCodeServlet.java. Here we use QRGen and ZXing to generate QR code from the text obtained from request.getParameter. Once the QR code stream is generated, we write it into the response and set the appropriate content-type.
QRCodeServlet.java
package net.viralpatel.qrcodes; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; 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 QRCodeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String qrtext = request.getParameter("qrtext"); ByteArrayOutputStream out = QRCode.from(qrtext).to(ImageType.PNG).stream(); response.setContentType("image/png"); response.setContentLength(out.size()); OutputStream outStream = response.getOutputStream(); outStream.write(out.toByteArray()); outStream.flush(); outStream.close(); } }
Use web.xml to map the /qrservlet request to QRCodeServlet.java.
web.xml
<!--?xml version="1.0" encoding="UTF-8"?--> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>QR_Code_Servlet</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>QRCodeServlet</servlet-name> <servlet-class>net.viralpatel.qrcodes.QRCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>QRCodeServlet</servlet-name> <url-pattern>/qrservlet</url-pattern> </servlet-mapping> </web-app>