Generate QR Code image from Java Program

Introduction to QR Codes
A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (“modes”) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCode {

public static void main(String[] args) throws WriterException, IOException, NotFoundException {

String qrCodeData = "Hello World!";
String charset = "UTF-8"; // or "ISO-8859-1"
Hashtable hintMap = new Hashtable();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
createQRCode(qrCodeData, charset, hintMap, 200, 200);
System.out.println("QR Code image created successfully!");
}

public static void createQRCode(String qrCodeData, String charset, Hashtable hintMap, int qrCodeheight, int qrCodewidth) throws WriterException, IOException {
String qrCodeFilePath = "C:\\QRCode.png";
BitMatrix matrix = new MultiFormatWriter().encode("Hello World", BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap);
MatrixToImageWriter.writeToFile(matrix, qrCodeFilePath .substring(qrCodeFilePath.lastIndexOf('.') + 1), new File( qrCodeFilePath));
}
}

Here is the QR Code image file created by this program. You can use your mobile QR Code scanner app to test it.

Comments

Popular posts from this blog

Edit/Modify existing PDF using Java(iText)

Verify Digital Signature in PDF using Java(iText) and cacerts

Steps to create SOAP Web service using Eclipse