Generating QR Codes in Java | ZXing library

  • Last updated Apr 25, 2024

QR Codes in Java can be generated 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 generate 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'
Generate QR Code

Here's a simple example that demonstrates how to generate a QR code for a given text:

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

public class QRCodeGenerator {
  private static final String QR_CODE_IMAGE_PATH = "./qrcode.png";

  public static void main(String[] args) {
    String text = "Hello, QR Code Buddy!";
    int width = 300;
    int height = 300;

    try {
      Map<EncodeHintType, Object> hints = new HashMap<>();
      hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

      BitMatrix bitMatrix =
          new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);

      BufferedImage qrImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          int grayValue = bitMatrix.get(x, y) ? 0 : 1;
          qrImage.setRGB(x, y, (grayValue == 0 ? Color.BLACK : Color.WHITE).getRGB());
        }
      }

      ImageIO.write(qrImage, "png", new File(QR_CODE_IMAGE_PATH));
      System.out.println("QR Code generated successfully.");
    } catch (Exception e) {
      System.out.println("Error generating QR Code: " + e.getMessage());
    }
  }

}

Run the QRCodeGenerator class. After running, you should find a qrcode.png file in your project directory containing the generated QR code.