Reading QR Codes in Java | ZXing library

  • Last updated Apr 25, 2024

QR Codes in Java can be read using ZXing library. ZXing ("zebra crossing") is an open-source library for reading and generating QR codes, including barcodes. Developed by Google, it offers comprehensive support for various barcode formats and is widely used in mobile applications and other software for barcode-related tasks.

Follow these steps to read a QR code in Java:

Add ZXing Dependency

Add zxing(core) and zxing(javase) to your project.

If you're using Maven, add the following dependency to your pom.xml:

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.5.2</version> <!-- Use the latest version -->
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.5.2</version> <!-- Use the latest version -->
</dependency>

If you're using Gradle, add the following dependency to your build.gradle:

implementation group: 'com.google.zxing', name: 'core', version: '3.5.2'
implementation group: 'com.google.zxing', name: 'javase', version: '3.5.2'
Read QR Code

Here's a simple example that demonstrates how to read a QR code from an image file:

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.Result;

public class QRCodeReader {

  public static void main(String args[]) {
    String filePath = "./qrcode.png"; // Path to your QR code image

    try {
      BufferedImage bufferedImage = ImageIO.read(new File(filePath));
      BinaryBitmap binaryBitmap =
          new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));

      Result result = new MultiFormatReader().decode(binaryBitmap);
      System.out.println("QR Code Content: " + result.getText());
    } catch (Exception e) {
      System.out.println("Error reading QR Code: " + e.getMessage());
    }
  }
  
}

Make sure you have a QR code image (example qrcode.png) in the specified path. Then, run the QRCodeReader class. The application will print the content of the QR code in the console.