Friday, January 12, 2018

Generating a QR code using QRGen-javase API

QRGen javase is a simple QRCode generation API which makes QR Code generation easy. In this example, I will show you how to generate a QR Code and save it as an image in two minutes.

Create a new maven project. Add below maven dependancy in to your pom.xml.
<dependency>
    <groupId>net.glxn.qrgen</groupId>
    <artifactId>javase</artifactId>
    <version>2.0</version>
</dependency>

I want to create the barcode so that when someone scanned the code he gets the URL to my blog http://tech-lead.blogspot.com. Below is the java class that I am using to generate this QR code.

import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import java.io.*;

public class CreateQrCode {
    public static void main(String[] args) {
        String url = "http://tech-lead.blogspot.com";
        String outputFile = "E:/qr.png";
        ByteArrayOutputStream bytes = QRCode.from(url).withSize(200, 200).to(ImageType.PNG).stream();

        try {
            OutputStream out = new FileOutputStream(outputFile);
            bytes.writeTo(out);
            out.flush();
            out.close();
            System.out.println("File created at " + outputFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Run the above main method and you will see the file is generated in the given location. See below image.