Core Java

How to Create QRCode Using QRGen in Java

In one of my previous articles, we saw how to create QRCode and its SVG equivalent using Zxing Java library. The Zxing library is no longer actively maintained and for this, there is a wrapper around Zxing library called QRGen, which provides much higher level APIs and a builder syntax for generating QR Codes.

In this article, we will see how to use QRGen library to generate QR code images.

Setting Up Maven Dependencies

The QRGen library is hosted on Mulesoft maven repository. You can use the below pom entries to include it in your application dependencies:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
<dependencies>
    <dependency>
        <groupId>com.github.kenglxn.qrgen</groupId>
        <artifactId>javase</artifactId>
        <version>2.5.0</version>
    </dependency>
</dependencies>
 
<repositories>
    <repository>
        <id>mulesoft</id>
    </repository>
</repositories>

Fluent Builder API for QR Code generation

The below code snippet shows the generation of QR code image, by default, it gets created in a temp file and we copy it into our project location by using Files.copy() :

01
02
03
04
05
06
07
08
09
10
11
12
File file = QRCode.from("www.google.com").to(ImageType.PNG)
        .withSize(200, 200)
        .file();
 
String fileName = "qrgen-qrcode.png";
 
Path path = Paths.get(fileName);
if ( Files.exists(path)){
    Files.delete(path);
}
 
Files.copy(file.toPath(), path);

Colorful QR Code

Using the fluent API, we can even generate a colorful QR code as shown below:

01
02
03
04
05
06
07
08
09
10
11
Path colorPath = Paths.get("qrgen-color-qrcode.png");
if ( Files.exists(colorPath)){
    Files.delete(colorPath);
}
 
file = QRCode.from("www.google.com")
        .withColor(Color.RED.getRGB(), Color.WHITE.getRGB())
        .withSize(200, 200)
        .withErrorCorrection(ErrorCorrectionLevel.Q)
        .file();
Files.copy(file.toPath(), colorPath);

The complete code can be downloaded from here.

Published on Java Code Geeks with permission by Mohamed Sanaulla, partner at our JCG program. See the original article here: How to Create QRCode Using QRGen in Java

Opinions expressed by Java Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button