The Wayback Machine - https://web.archive.org/web/20240720213820/https://www.geeksforgeeks.org/how-to-generate-and-read-qr-code-with-java-using-zxing-library/
Open In App

How to generate and read QR code with Java using ZXing Library

Last Updated : 21 Mar, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

QRCode is abbreviated as Quick Response Code, and we are quite familiar with QRCodes now a days. It is used for authenticated and quick online payments. A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to store data efficiently; extensions may also be used.
A QRCode is an arrangement of black and white squares and can be read with various QRCode Scanners and is convenient today because every smartphone has a QRcode scanner app.

Library used for generating QRCodes (ZXing)

ZXing (“Zebra Crossing”) is the popular API for QR code processing in Java. Its library has multiple components, and we will be using the ‘core’ for QR code creation in our Java example. 

Method to generate a QR code

The following code is an example of creating a QR code image.

  • Download the ZXING library from here. 
  • Add ZXING dependency in the Maven file.
<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>

Program to generate QR code and save it as a jpg file in the native folder

Java
// Java code to generate QR code
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class MyQr {

    // Function to create the QR code
    public static void createQR(String data, String path,
                                String charset, Map hashMap,
                                int height, int width)
        throws WriterException, IOException
    {

        BitMatrix matrix = new MultiFormatWriter().encode(
            new String(data.getBytes(charset), charset),
            BarcodeFormat.QR_CODE, width, height);

        MatrixToImageWriter.writeToFile(
            matrix,
            path.substring(path.lastIndexOf('.') + 1),
            new File(path));
    }
  
    // Driver code
    public static void main(String[] args)
        throws WriterException, IOException,
               NotFoundException
    {

        // The data that the QR code will contain
        String data = "www.geeksforgeeks.org";

        // The path where the image will get saved
        String path = "demo.png";

        // Encoding charset
        String charset = "UTF-8";

        Map<EncodeHintType, ErrorCorrectionLevel> hashMap
            = new HashMap<EncodeHintType,
                          ErrorCorrectionLevel>();

        hashMap.put(EncodeHintType.ERROR_CORRECTION,
                    ErrorCorrectionLevel.L);

        // Create the QR code and save
        // in the specified folder
        // as a jpg file
        createQR(data, path, charset, hashMap, 200, 200);
        System.out.println("QR Code Generated!!! ");
    }
}

Output:

The output file will be by name demo.jpg.

QR code Output

On scanning this QRCode, you will be redirected to geeksforgeeks home page. 

Read a QR Code

After generating the QR code, we can also read the QR code image file using ZXing library. Below is the code to do so.

Java
// Java code to read the QR code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCode {

    
    // Function to read the QR file
    public static String readQR(String path, String charset,
                                Map hashMap)
        throws FileNotFoundException, IOException,
               NotFoundException
    {
        BinaryBitmap binaryBitmap
            = new BinaryBitmap(new HybridBinarizer(
                new BufferedImageLuminanceSource(
                    ImageIO.read(
                        new FileInputStream(path)))));

        Result result
            = new MultiFormatReader().decode(binaryBitmap);

        return result.getText();
    }
  
    // Driver code
    public static void main(String[] args)
        throws WriterException, IOException,
               NotFoundException
    {

        // Path where the QR code is saved
        String filePath = "F:\\user\\QRCodes";

        // Encoding charset
        String charset = "UTF-8";

        Map<EncodeHintType, ErrorCorrectionLevel> hashMap
            = new HashMap<EncodeHintType,
                          ErrorCorrectionLevel>();

        hashMap.put(EncodeHintType.ERROR_CORRECTION,
                    ErrorCorrectionLevel.L);

        System.out.println(
            "QRCode output: "
            + readQR(filePath, charset, hashMap));
    }

}

Output: 

QRCode output: www.geeksforgeeks.org


Similar Reads

Java Program to Convert Binary Code Into Equivalent Gray Code Using Recursion
Convert the Binary code of the Number into it's equivalent Gray's code using recursion. Binary is the default way to store numbers, but in many applications, binary numbers are not useful and a variation of binary is needed. Gray code has the property that two successive numbers differ in only one bit and used in K-maps, error correction, and commu
3 min read
Java Program to Convert Binary Code into Gray Code Without Using Recursion
Binary Code of a number is the representation of a number in Binary (base-2) number system. In Binary Number System, each number is expressed using only two literals (0 and 1). Each of these literals is called a bit. The binary number system is very useful in digital electronic circuits. Gray Code of a number is the representation of a number using
4 min read
How to Read and Write Files Using the New I/O (NIO.2) API in Java?
In this article, we will learn how to read and write files using the new I/O (NIO) API in Java. For this first, we need to import the file from the NIO package in Java. This NIO.2 is introduced from the Java 7 version. This provides a more efficient way of handling input and output operations compared to the traditional Java package java.io. Now, b
3 min read
Java Program to Validate Phone Numbers using Google's libphonenumber Library
Validating phone numbers is a common prerequisite in today’s web, mobile, or desktop applications, but Java does not have an integrated method for carrying out this kind of common validation. So, we have to use some open source libraries to perform such validation. One such library is Google’s phone number library. It helps to verify any phone numb
4 min read
How to Convert String to Char Stream in Java without Using Library Functions?
In Java, we can convert a string to a char stream with a simple built-in method .toCharArray(). Here, we want to convert the string to a char stream without using built-in library functions. So, we will create an empty char array iterate it with string characters, and store the individual characters from the string to the char array one after the o
2 min read
Java Program to Read Elements using Enumeration in Hashtable
The enumeration in java is one of the predefined interfaces, whose object is used for retrieving the data from collections framework variable(like Stack, Vector, HashTable, etc.) in a forward direction only and not in the backward direction. HashTable is a class The hash table class implements a Map, which maps keys to values. It stores the key/val
3 min read
How to Read Write Object's Data in CSV Format Using Notepad in Java?
The CSV stands for Comma-Separated Values. CSV files can be used with almost any spreadsheet program, such as Microsoft Excel or Google Spreadsheets. They differ from other spreadsheet file types because you can only have a single sheet in a file, they can not save cell, column, or row. Also, you cannot save formulas in this format. Now, to store o
7 min read
Java Program to Read and Print All Files From a Zip File
A zip file is a file where one or more files are compressed together, generally, zip files are ideal for storing large files. Here the zip file will first read and at the same time printing the contents of a zip file using a java program using the java.util.zip.ZipEntry class for marking the zip file and after reading it, the contents inside it wou
4 min read
Java Program to Read Content From One File and Write it into Another File
File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. Now in order to read conte
5 min read
Image Processing in Java - Read and Write
Java implements a particular type of object called a BufferedImage for images in Java. A BufferedImage can be read from several distinct image types (i.e., BMP, HEIC, etc.). Not all of these are backed by ImageIO itself, but there are plugins to extend ImageIO and other libraries such as Apache Imaging and JDeli. In Java itself, all the complexity
3 min read
three90RightbarBannerImg