Create Quick Response Code (QR code) in Java example


             QR code (Quick Response code), a 2D bar-code,  uses four standardized encoding modes (numeric, alphanumeric, byte / binary, and kanji) to efficiently store data; extensions may also be used.It was initially used to track parts in vehicle manufacturing, which are now used over a much wider range of applications.

              As the name suggests, the Quick Response code helps customers to find valuable information fast. QR codes are used in transport ticketing, entertainment, commercial tracking, and product labeling/marketing, just to name a few. This is becoming very popular in mobile apps also, where you scan the QR code using a QR Code scanner app and it will show you the text or redirect you to the web page if it’s URL.
Here is an example area where you can see QRCode:

QR Code in product tag
              This tutorial aims to explain on how to create QR code in java with an example which is explained in detail below. Source code is also attached at the bottom.            
To make the task easy for us, there are many open source APIs available in the market. But the simplest and easy to use API is zxing (Zebra Crossing). To get started, we need to download zxing – ‘core’ and ‘javase’ jar files (click here to download them).
                If you are using any IDE for the development, add the downloaded jar files to the libraries folder.If you are running your application in command line, add the path of the jar files to classpath.
Once done with it, we are ready to play with QR codes.

Steps to create QRCode using java:
QRCode can be created using two simple steps described below:

Step -1: Create BitMatrix out of the given data
               To create a BitMatrix, we make use of MultiFormatWriter factory class which finds the appropriate Writer subclass for the BarcodeFormat requested and encodes the barcode with the supplied contents.

BitMatrix matrix = new MultiFormatWriter().encode(new String(qrCodeData.getBytes(charset),charset),BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap);
The parameters we supply for the encode function using MultiFormatWriter are:

qrCodeData       - The content to encode in the barcode (convert the content to be encoded into UTF-                                8 character set)
BarcodeFormat - The barcode format to generate (QR_CODE in our case)
qrCodewidth     - The preferred width in pixels
qrCodeheight    - The preferred height in pixels
hintMap            - Additional parameters to supply to the encoder.

Note: The hint type we have given is error correction. It specifies what degree of error correction to use. The one which we have used is L (L = ~7% correction). Below is the code snippet used to specify the error correction level in hintMap.
Map hintMap = new HashMap();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

Step-2: Convert the BitMatrix into QRimage

MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath.lastIndexOf('.') + 1), new File(filePath));

Converting the BitMatrix to QRimage can be done using MatrixToImageWriter. This class helps us to write the BitMatrix to BufferedImage, file or stream.
Our main focus is to create a QRimage file for the given content. Hence we make use of the method writeToFile(). The parameters for this method are:

matrix            - The BitMatrix we have created
imageFormat - extracted from the filePath using the below code
file                 - file to write the image to

filePath.substring(filePath.lastIndexOf('.') + 1)
(If the filePath we have specified is E:/QRCode/qr_img.png, the above code will return 'png'.
Note: Any of the image formats can be given)

Output Screenshot:

Program Output

Thats it !! We have created our own QR code , go to the mentioned path and check for it.. You should be able to see an image like below...
Next post will explain you on how to read this QR Code using java... Stay tuned !!
QR Code created

import java.util.HashMap;
import java.util.Map;

public class QRCode {

 public static void main(String[] args) throws WriterException, IOException,
   NotFoundException {
  String qrCodeData = "";
  String filePath = "E:/cte.png";
  String charset = "UTF-8"; // or "ISO-8859-1"
  Map hintMap = new HashMap();
  hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
  createQRCode(qrCodeData, filePath, charset, hintMap, 200, 200);
  System.out.println("QR Code image created successfully!");


 public static void createQRCode(String qrCodeData, String filePath,
   String charset, Map hintMap, int qrCodeheight, int qrCodewidth)
   throws WriterException, IOException {
  BitMatrix matrix = new MultiFormatWriter().encode(
    new String(qrCodeData.getBytes(charset), charset),
    BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap);
  MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath
    .lastIndexOf('.') + 1), new File(filePath));

Source code of this Application:

No comments:
Write comments

Popular Posts