Showing posts with label ZXing QR Code. Show all posts
Showing posts with label ZXing QR Code. Show all posts

Wednesday, April 30, 2014

Java QR Code Decoder using ZXing


Today, I came across a requirement in my office project where I had to scan some QR codes in Java. For that we used Tasman Barcode Recognition software owned by Accusoft. Then I was interested to see if there are any free and open source softwares for QR Code encoding/decoding. Then I came across ZXing ("zebra crossing") which is a multi-format 1D/2D barcode/qrcode image processing library implemented in Java, with ports to other languages as well.

Below is the example of how a QR Code image can be decoded using ZXing librabry.

Library Downloads:

You'll need two jars core.jar and javase.jar which can be downloaded from here:

  • Core: http://repo1.maven.org/maven2/com/google/zxing/core/
  • Javase: http://repo1.maven.org/maven2/com/google/zxing/javase/

Steps:

1. Create a Java Project.

  • The following is the project I created in eclipse. 


2. Create a folder "libs" in the above example and put the jars into the folder.

3. Add the jars to the Project Build Path:

  • Right click on the project -> Properties -> Java Build Path -> Libraries Tab -> Add JARs...



4. Create a main class as follows:

package com.qrcode.decoder;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class QRCodeDecoder {
       public static void main(String[] args) throws IOException {

              File imageFile = new File("D:\\image.png");

              BufferedImage image = ImageIO.read(imageFile);

              try {
                     LuminanceSource source = new BufferedImageLuminanceSource(image);

                     BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                     Reader reader = new MultiFormatReader();
                     Result result = reader.decode(bitmap);

                     System.out.println("Barcode text: " + result.getText());
              } catch (Exception e) {
                     e.printStackTrace();
              }
       }
}


5. DONE.

Userful Reference:

https://github.com/zxing/zxing/