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
December 18, 2012

Hi I was wondering if you could guide me in creating the Qrcode in android without using zxing. The problem with porting the above application is that awt and javax libraries are not compatible in android

- Don Peter

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 7, 2013

    I watched the passage which provides a qr code Java class library to create qr code image in android application. It might be helpful!

    - Taylor

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      March 23, 2013

      hi can u please guide me in developing a color 2D barcode…?

      - lidiya

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        March 29, 2013

        how to control the qrcode image size 0.74cm *0.74cm

        - wuwang

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          June 22, 2013

          are there any java lib to embedded image into qr code?

          - Hoa

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 27, 2013

            i want to get a text from jtextfirld and show the QR code as a jlabel when a button is pressed. Please provide me java code for it.

            - Prabhat Kumar

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              September 13, 2013

              can u mail me code for qr code encode and decode for android

              - mahesh bhanushali

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                September 18, 2013

                can you give code for qr code scanner

                - mahesh bhanushali

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  November 8, 2013

                  Hello, I downloaded the axing ell from the site you posted and tried your sample code, but it appears that get_Renamed is not a method. I am using zing.monoandroid.dll. Do you know why I would not see get_Renamed? Any help is appreciated!!

                  - Tony

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    April 1, 2014

                    Thank you sir for your post Generate QR code using java…Sir in this program zxing api is used which is not built in api of jvm…would you please give me your valuable guide to how to run this program …

                    - prerna verma

                      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!

                      Become a contributor for community

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

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.