Build a Java QR Code Generator with ZXing in 15 Minutes

Java QR Code Generator: Step-by-Step Guide for Beginners

QR codes are a fast, reliable way to encode URLs, contact details, and other small data in a scannable image. This guide walks you through building a simple Java QR code generator using the popular ZXing library. No prior QR experience required — follow the steps and you’ll have a reusable utility that produces PNG QR codes with configurable size, color, and error correction.

What you’ll need

  • Java 11+ (or any recent Java version)
  • Maven or Gradle for dependency management
  • A text editor or IDE (IntelliJ, Eclipse, VS Code)
  • ZXing core and JavaSE modules

Step 1 — Create a new project

Set up a basic Maven project. Example pom.xml dependencies:

xml

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

(If you use Gradle, add the equivalent to build.gradle.)

Step 2 — Basic QR generator code

Create a Java class (QrGenerator.java). This example produces a PNG file from input text:

java

import com.google.zxing.*; import com.google.zxing.client.j2se.MatrixToImageConfig; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; public class QrGenerator { public static void generate(String text, int size, Path outputFile) throws Exception { Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, “UTF-8”); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // L, M, Q, H hints.put(EncodeHintType.MARGIN, 1); BitMatrix matrix = new MultiFormatWriter() .encode(text, BarcodeFormat.QR_CODE, size, size, hints); // Optional: customize colors (foreground, background) int fg = 0xFF000000; // black int bg = 0xFFFFFFFF; // white MatrixToImageConfig config = new MatrixToImageConfig(fg, bg); MatrixToImageWriter.writeToPath(matrix, “PNG”, outputFile, config); } public static void main(String[] args) throws Exception { String text = args.length > 0 ? args[0] : https://example.com”; int size = 300; Path out = Paths.get(“qrcode.png”); generate(text, size, out); System.out.println(“QR written to “ + out.toAbsolutePath()); } }

Step 3 — Run and test

  • Build with Maven: mvn package
  • Run: java -cp target/your-jar.jar QrGenerator “https://your-site.example
  • Open the generated qrcode.png and scan with your phone.

Step 4 — Customization options

  • Size: change the size parameter (e.g., 150–1000 px).
  • Error correction: use ErrorCorrectionLevel.L/M/Q/H (higher = more redundancy, larger/denser QR).
  • Margin: adjust EncodeHintType.MARGIN (0–4) to control white border.
  • Colors: change fg/bg in MatrixToImageConfig for branding.
  • Output formats: write to JPG or write image to an OutputStream for web responses.

Step 5 — Embedding in web apps

  • For Java servlets or Spring Boot controllers, write the image to the HTTP response OutputStream with content-type image/png.
  • Example (Spring Boot):

java

@GetMapping(”/qrcode”) public void qrcode(@RequestParam String text, HttpServletResponse resp) throws Exception { resp.setContentType(“image/png”); Path tmp = Files.createTempFile(“qr”, ”.png”); QrGenerator.generate(text, 300, tmp); Files.copy(tmp, resp.getOutputStream()); Files.delete(tmp); }

Step 6 — Error handling & security notes

  • Validate input length — QR codes have capacity limits depending on charset and error correction.
  • Sanitize user-provided URLs if embedding in pages.
  • Avoid storing sensitive personal data in QR codes unless encrypted.

Troubleshooting

  • Blurry image when scanned: increase size or error correction.
  • Not encoding special characters: ensure CHARACTER_SET is UTF-8.
  • Library conflicts: ensure only one ZXing version on the classpath.

Quick reference: common QR capacities (approx.)

  • Numeric only: up to ~7,000 digits
  • Alphanumeric: up to ~4,200 characters
  • Binary (bytes): up to ~2,900 bytes Actual capacity depends on error correction and version.

This gives you a working Java QR code generator you can expand for web apps, batch generation, or custom styling.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *