Java — Read QR Code using zxing | Code Factory

Donate : Link

WordPress Blog : Link

Generate QR Code Article : Link

We’ll use Google’s zxing library to read QR code images.

Please make sure that following zxing dependencies are added in your pom.xml file

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

QRCodeReader.java

package com.example.java.programming;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.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
/**
* @author code.factory
*
*/
public class QRCodeReader {
private static final String IMAGE_PATH = "QR.png"; public static void main(String... args) {
try {
File file = new File(IMAGE_PATH);
String str = readQRCode(file);
if (str == null) {
System.out.println("No QR Code found in the Image.");
} else {
System.out.println("Decoded = " + str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String readQRCode(File file) throws IOException {
BufferedImage bufferedImage = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
Result result = new MultiFormatReader().decode(bitmap);
return result.getText();
} catch (NotFoundException e) {
System.out.println("There is no QR code in the Image.");
return null;
}
}
}

Output :

Decoded = Code Factory