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:

<dependencies>
	<!-- https://mvnrepository.com/artifact/com.github.kenglxn.qrgen/javase -->
	<dependency>
		<groupId>com.github.kenglxn.qrgen</groupId>
		<artifactId>javase</artifactId>
		<version>2.5.0</version>
	</dependency>
</dependencies>

<repositories>
	<repository>
		<id>mulesoft</id>
		<url>https://repository.mulesoft.org/nexus/content/repositories/public/</url>
	</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() :

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:

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.

Categories: Java

Tagged as: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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