Booked a movie ticket recently and got the ticket in the form of a QR Code?

Sent money to your friend’s mobile wallet using his QR Code?

Well, If you’re not living in Antarctica or Mount Everest, then chances are that you might have heard about or used QR Codes in your life.

If you wanted to know how QR Codes work and how to generate one for your next exciting project, then this blog post is for you.

What are QR Codes?

QR Code or Quick Response Code is a two dimensional barcode that can be read by modern smartphones and special QR Code scanner devices.

A QR code consists of black squares arranged in a square grid on a white background. There are several variants of QR codes depending on their symbol size, layout, encoding and structure.

Following is an image of a typical QR Code (I’ve encoded something in this QR Code image. Scan it from your smartphone to check what’s inside :-) -

QR Code example

QR Codes can be used to encode various types of data like - simple text, urls, phone numbers, sms, geolocation, email address etc.

In the next section, we’ll learn how to encode such data and generate the QR Code in Java.

How to generate QR Code in Java?

We’ll use Google’s Zxing library to generate QR codes for our application.

Zxing, pronounced as Zebra Crossing, is an open source, multi-format 1D/2D barcode image processing library implemented in java.

1. Add Zxing dependencies

If you use maven, then add the following dependencies in your pom.xml file to include zxing in your project -

<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>	

Android users, or other gradle users can add the following to their build.gradle file -

compile "com.google.zxing:core:3.3.0"
compile 'com.google.zxing:javase:3.3.0'

If you are not using any build system then just download the following zxing jars hosted on Maven release repository and add them in the classpath -

2. Program to generate QR Code

In the following program, I’ve written a method called generateQRCodeImage which takes the text to be encoded, the width and height of the QR Code, and the file system’s path where QR Code will be saved.

The function generates and saves the QR Code in the specified path.

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

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

    private static void generateQRCodeImage(String text, int width, int height, String filePath)
            throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    public static void main(String[] args) {
        try {
            generateQRCodeImage("This is my first QR Code", 350, 350, QR_CODE_IMAGE_PATH);
        } catch (WriterException e) {
            System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
        }
    }
}

The above program will generate a QR Code with text - “This is my first QR Code” and save it in the specified location. Here is the generated QR Code -

Generated QR Code in Java

The above generateQRCode method writes the QRCode image into the specified location. If you don’t want to save the QRCode and want to return it from the function as a byte array, then you can use MatrixToImageWriter.writeToStream() method provided by zxing library -

/* 
This method takes the text to be encoded, the width and height of the QR Code, 
and returns the QR Code in the form of a byte array.
*/
private byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
    
    ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
    byte[] pngData = pngOutputStream.toByteArray(); 
    return pngData;
}

The above method is very useful -

  • If you’re developing a web application and want to return the QR Code image as a response to an http request. You can return the byte array in the body of your http response.

  • If you’re developing an android application and want to display the QR Code on your activity screen. You can convert the byte array into a BitMap and display the image in an ImageView.

Securing your QR Codes

The text that is encoded using QR Code can be read and interpreted by any smart phone and qr code scanner devices. But, What if you don’t want everyone to read what is encoded in the QR Code?

Well, QR Code itself does not provide any security. Here is what you can do instead -

  • Before generating QR code with any text, encrypt the text using any cryptographic algorithm with a secret that only your application has access to.

  • Generate QR Code with the encrypted text.

Now, even if someone scans your QR Code, they will get the encrypted text which they can’t decrypt unless they know the secret which was used to encrypt it.

But when you scan the QR Code in your application, you can decrypt the text using the secret and get the actual data stored in the QR Code.

Conclusion

In this post, we learned how to generate QR codes in java using google’s zxing library. In the next post, we’ll learn how to read QR code images in Java.

You can find all the code samples in my github repository.

Thank you for reading. Please ask any doubts in the comment section below.