Step 01:
Add below to your maven repository.
<!-- https://mvnrepository.com/artifact/net.glxn/qrgen -->
<dependency>
<groupId>net.glxn</groupId>
<artifactId>qrgen</artifactId>
<version>1.4</version>
</dependency>
Step 02:
Add below java util class in to your project and use it as you want. Please note this util class is coded as I wanted, you can amend the code as you want; anyway I added comments to describe the code for you.
package lk.pwc.cult.fund.common.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
//importing libraries
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class QRCodeUtil {
//pass a string generated code to embed in the qr code
public String retrieveQRCodeImageName(String code) {
try {
//generating the qr code in png format and get to Byte Array Output Stream
ByteArrayOutputStream out = QRCode.from(code).to(ImageType.PNG).stream();
//get file path from the property file to save the created qr code png
String filePath = CommonUtil.getValueFromFile("application", "qrcode.file.location");
//generate a random string to save the qr coded png file
String fileName = UUID.randomUUID().toString() + ".png";
String imagePath = filePath + fileName;
//this set of code uses to create the specific file path if it's not exist
File theDir = new File(filePath);
if (!theDir.exists()) {
try {
theDir.mkdirs();
System.out.println("DIR created");
} catch (SecurityException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
FileOutputStream fout = new FileOutputStream(new File(imagePath));
//Use file output stream to write the qr code png image to a file
fout.write(out.toByteArray());
fout.flush();
fout.close();
return imagePath;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}