Java QR Code

Quick Response Code (QR Code) is a two-dimensional matrix like barcode, designed by a subsidiary of Toyota to mark their vehicles for tracking in their manufacturing facilities. This is nothing but a type of barcode.

The four standard modes of data for creating QR code is numeric, alphanumeric, byte / binary and Kanji. There are extensions to these standard types available, using which custom data also can be coded.

So why is it popular? QR code can store more volume of data in small area compared to the standard barcode formats. Any place where the barcodes are being used can be replace by QR codes.

QR Code
Can you scan and comment on what is in this picture?

This became easily popular because of the advent of mobile apps that can be used as a QR code scanner to read the information in QR codes. You can see advertisements in newspapers having QR codes. It may contain product information, price detail, web url, etc. If you have a smartphone with iOS or Android then you can install a QR Code app easily in a minute and scan all those codes to read the information.

Some general uses of QR codes are,

  • contact information
  • calendar event
  • URL
  • GEO location
  • website authentication
  • credit card information

Java API for QR Code

ZXing ("Zebra Crossing") is the popular API for QR code processing in Java. Its library has multiple components and we will be using the ‘core’ for QR code creation in our Java example. Following code is example to create a QR code image and read information from a QR code image.

QR Code Write and Read Program in Java

package com.javapapers.java;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCode {

	public static void main(String[] args) throws WriterException, IOException,
			NotFoundException {
		String qrCodeData = "Hello World!";
		String filePath = "QRCode.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!");

		System.out.println("Data read from QR Code: "
				+ readQRCode(filePath, charset, hintMap));

	}

	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));
	}

	public static String readQRCode(String filePath, String charset, Map hintMap)
			throws FileNotFoundException, IOException, NotFoundException {
		BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
				new BufferedImageLuminanceSource(
						ImageIO.read(new FileInputStream(filePath)))));
		Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap,
				hintMap);
		return qrCodeResult.getText();
	}
}

QR Code Write and Read Program Output

QR Code Output

Maven dependency for the ZXing QR Code library:

<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>core</artifactId>
	<version>2.2</version>
</dependency>

<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>javase</artifactId>
	<version>2.2</version>
</dependency>
            

This Core Java tutorial was added on 15/10/2013.

Comments on "Java QR Code" Tutorial:

  1. Chitra Priya says:

    Your sample project works superb! Thanks for this nice tutorial. I learned this new today :-)

  2. Vincy says:

    Interesting!

    Happy to see this article.

    Thank You!

  3. Joe says:

    Welcome Chitra.

  4. Arup says:

    Thanx Joe.

  5. Anonymous says:

    Again a Nice one Joe :)

  6. Joe says:

    Welcome Arup.

  7. Kasuntha says:

    Thanks.. Really helpfull..

  8. paritosh says:

    Nice article. Thank you Joe.

  9. swapna says:

    Hi Joe,

    Nice example.Do you have the knowledge about capcha.Now a days in so many websites we are asking for capcha.What is use of it and how it will be helpful or exactly its purpose.

  10. Bonny Gabriel says:

    Thank You Joe. You are a gem to the society.

  11. Joe says:

    Sure Swapna. I will write about it quite soon.

  12. Joe says:

    :-O really, thanks a lot.

  13. lmfduarte says:

    Hi,

    I put zxing.jar (version 2.2) in my libraries on exclipse, but I have an error in this 2 lines:

    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filePath)))));
    Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, hintMap);

    BufferedImageLuminanceSource and HybridBinarizer are not recognized.
    Can you help me please

  14. Ritu Rai says:

    Thanks Joe :)

  15. Joe says:

    You need to add two jar files and they are,

    1. core-2.2.jar
    2. javase-2.2.jar

    They can be downloaded from zxing maven repository or it is there in the example project I have done along with the tutorial.

    As of now, the jar files are not provided by zxing along with their regular downloads. They provide only the source files. Either we need to compile the jar from their project or download it from the maven repository.

  16. Joe says:

    Welcome Ritu.

  17. lmfduarte says:

    Works good.

    Thank you Joe and keep up the good work!

  18. Pratik says:

    Thanks Joe, with this article I came to know what exactly QR is.

  19. Anu says:

    Very nice article. Learnt something new today..Thanks Joe

  20. Joe says:

    Welcome Pratik.

  21. Joe says:

    Welcome Anu.

  22. Arif says:

    Hi Joe , very nice tutorial. I looking for a java library for sending sms from usb GSM modem via GSM Network. I need it for my accademic project .Can you help me or suggest me please ? Thanks.

  23. Chennu says:

    Hi Joe,

    Excellent one. From this example, whatever we written in the image, we can able to read. Can you please let us know how to read data from the existing/written by others QR images.

  24. Joe says:

    If you have the QR image is printed in paper, then we can read it using mobile apps. There are free apps available for Android, iOS and other mobile OS.

  25. Srinu says:

    Super sir

  26. Niraj says:

    good sir

  27. Suresh says:

    nice sir

  28. Padma says:

    Very Nice article… keep up the good work of being blessed to all javaites.

  29. Murthy says:

    Excellent ..very usefull

  30. Dnyaneshwar Pote says:

    it’s nice tutorial it helped me… thanks.

  31. aishwarya says:

    Thanks a lot Joe.. I could generate QR codes of different colours easily. Could you please tell how to display this in a webpage. i.e) everytime we hit submit a different QR code should be dynamically generated.

  32. Tangmo says:

    Thank you so much… Joe ^___^

  33. Vlad says:

    Checkout ShieldUI for Wicket library available on github.
    It has a nice barcode component rendered on the client side

  34. Rakesh says:

    good tutorial, with sample code and dependencies info.

    Thanks

  35. Adil says:

    Very good code.

    I hope to make a Java mobile app from this for Nokia.

    Thanks

  36. Octavian says:

    very useful code, especially when u are in a hurry like in a hackathon :)
    Tx

  37. Firoz Shaikh says:

    By This Tutorial I learn something Different today. Thanks a lot sir…

  38. Hidetoshi says:

    Thanks for great sample!
    But it does not work when qrCodeData includes Kanji.
    Looks need to add
    hintMap.put(EncodeHintType.CHARACTER_SET, charset);

  39. yadhi says:

    working fine, thank you.

  40. Gus says:

    Hi, I’m trying to read a text QR code, UTF-8 does not work, neither the other option. Any help?

  41. pho says:

    hi,thank you for this neat tutorial, works very well. Is it possible to encode a sql query result set into a QR CODE

  42. Vinh says:

    Thanks for a nice tutorial. Can you update this tutorial and show us how to print out barcode image to thermal printer? Thank you.

Comments are closed for this "Java QR Code" tutorial.

↑ Go to top