Monday 17 May 2021

Java: Create QR code

Below snippet is used to generate qr code.

Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

BitMatrix bitMatrix = new MultiFormatWriter().encode(new String(message.getBytes(encodingFormat)),BarcodeFormat.QR_CODE, imageHeight, imageWidth);

String fileFormat = filePath.substring(filePath.lastIndexOf('.') + 1);
MatrixToImageWriter.writeToPath(bitMatrix, fileFormat, Paths.get(filePath));

 

Find the below working application.

 

QRCodeUtil.java

 

package com.sample.app.util;

import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCodeUtil {

	public static boolean generateQRCode(String message, String filePath, Charset encodingFormat, int imageHeight,
			int imageWidth) {

		try {
			Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
			hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

			BitMatrix bitMatrix = new MultiFormatWriter().encode(new String(message.getBytes(encodingFormat)),
					BarcodeFormat.QR_CODE, imageHeight, imageWidth);

			String fileFormat = filePath.substring(filePath.lastIndexOf('.') + 1);
			MatrixToImageWriter.writeToPath(bitMatrix, fileFormat, Paths.get(filePath));
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

}


QrCodeGenerateDemo.java

package com.sample.app;

import java.nio.charset.StandardCharsets;

import com.sample.app.util.QRCodeUtil;

public class QrCodeGenerateDemo {

	public static void main(String args[]) {
		String filePath = "/Users/Shared/secret.png";

		boolean isQRCodeGenerated = QRCodeUtil.generateQRCode("Transfer 1000 from account A to Account B", filePath,
				StandardCharsets.UTF_8, 250, 250);

		if (isQRCodeGenerated) {
			System.out.println("QR code generated successfully");
		} else {
			System.out.println("QR code generation failed");
		}
	}
}


Output

QR code generated successfully

 

Generated secret.png file


Previous                                                    Next                                                    Home

No comments:

Post a Comment