Tutorial

Java QR Code Generator - zxing example

Published on August 3, 2022
author

Pankaj

Java QR Code Generator - zxing example

Today we will look into the Java QR code generator program. If you are tech and gadget savvy, then you must be aware of the QR code. You will find it everywhere these days - in blogs, websites, and even in some public places. This is very popular in mobile apps, where you scan the QR code using a QR Code scanner app and it will show you the text or redirect you to the web page if it’s URL. I came across this recently and found it very interesting. If you want to know about QR Code, you can find a lot of useful information at Wikipedia QR Code Page.

Java QR code generator

When I found QR code images on so many websites, I started looking for java QR code generator. I looked into some open source APIs and found zxing to be the simple and best to use. If you want to generate a QR code image, then we only need its core library. Just add below dependency to your maven project.

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

If you want to read QR image through the command line, then we need to use it’s JavaSE library. You can add below dependency for it.

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

This will also let you know two extra dependencies required to run from the command line, as shown in the below image. We will have to add these jars into classpath to run the client app to read the QR code image. We will see this in action later on in this tutorial. zxing maven dependencies

zxing example to generate QR code image

Here is the program you can use to create QR Code image with zxing API. GenerateQRCode.java

package com.journaldev.qrcode.generator;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class GenerateQRCode {

	public static void main(String[] args) throws WriterException, IOException {
		String qrCodeText = "https://www.journaldev.com";
		String filePath = "JD.png";
		int size = 125;
		String fileType = "png";
		File qrFile = new File(filePath);
		createQRImage(qrFile, qrCodeText, size, fileType);
		System.out.println("DONE");
	}

	private static void createQRImage(File qrFile, String qrCodeText, int size, String fileType)
			throws WriterException, IOException {
		// Create the ByteMatrix for the QR-Code that encodes the given String
		Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
		hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, size, size, hintMap);
		// Make the BufferedImage that are to hold the QRCode
		int matrixWidth = byteMatrix.getWidth();
		BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
		image.createGraphics();

		Graphics2D graphics = (Graphics2D) image.getGraphics();
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, matrixWidth, matrixWidth);
		// Paint and save the image using the ByteMatrix
		graphics.setColor(Color.BLACK);

		for (int i = 0; i < matrixWidth; i++) {
			for (int j = 0; j < matrixWidth; j++) {
				if (byteMatrix.get(i, j)) {
					graphics.fillRect(i, j, 1, 1);
				}
			}
		}
		ImageIO.write(image, fileType, qrFile);
	}

}

Here is the QR Code image file created by this program. You can use your mobile QR Code scanner app to test it. It should point to JournalDev Home URL. java qr code generator, zxing example

zxing example to read QR code

If you don’t have a mobile app to test it, don’t worry. You can read QR code with zxing API through the command line. Below is the command to read the QR code image file. Notice the additional jars in the classpath that zxing depends on.

$java -cp $HOME/.m2/repository/com/google/zxing/javase/3.3.2/javase-3.3.2.jar:.:$HOME/.m2/repository/com/google/zxing/core/3.3.2/core-3.3.2.jar:$HOME/.m2/repository/com/beust/jcommander/1.72/jcommander-1.72.jar:$HOME/.m2/repository/com/github/jai-imageio/jai-imageio-core/1.3.1/jai-imageio-core-1.3.1.jar com.google.zxing.client.j2se.CommandLineRunner JD.png

The below image shows the output produced by this command. zxing read qr code image

You can download the QR Code Generator and Reader maven project from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 8, 2022

Hi I PUT THE QR code in inclipse it says done but i dont know where the image is stored. it says jd.png where is that. thanks

- jeff

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 10, 2020

    Very well done. Other zxing code produces errors. Thank you.

    - cpanon

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      February 4, 2020

      Hi, I got an error from line : image.createGraphics(); while running in linux server. Caused by: java.awt.AWTError: Can’t connect to X11 window server using ‘:0.0’ as the value of the DISPLAY variable.

      - Alz

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 21, 2019

        the qrcode not always working with the jframe it is showing the previous qrcode information. please help!

        - Akash Kandwal

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 14, 2018

          How do I change a version of QR Code? is coming out with version 2 but would like to switch to version 1 (25x25). thank you

          - Ricardo

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 3, 2018

            can u give code for eclipse,for generatin barcode and qr code using zxing core.jarand javase.jar files,please help

            - aayesha

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              January 17, 2018

              sir, my name is A.CHAITANYA. I am doing my master’s in IIITDM KANCHEEPURAM College. In my final year project, I am doing watermarking with QR code. So i need a verilog code to generate a QR code. So can you please send me the verilog code. Thank you sir.

              - A.V.V.Y.CHAITANYA

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 1, 2017

                how to encode a secret message into qr code?

                - supriya

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  December 20, 2016

                  Is there a way i can scan external QR codes from a PC (by way of a physically attached scanner) and capture the result/output for processing through a Java API (ZXing??) in a ‘seamless’ manner?

                  - Bell

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    November 24, 2016

                    its very nice bro

                    - bala

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more