create QR Codes in Java

Bar codes aren’t just for cereal boxes any more. 2-D barcodes like Quick Response (QR) Codes are easily read by smart phones and are showing up everywhere from magazinee, restaurant fronts, advertisement, & business cards. With some of the open-source libraries out there, it’s not hard to create your own QR Codes with java.To generate a quick code for standard content,  So how would you encode ‘krishna’ in a QR Code?

The good folks working on ZXing (http://code.google.com/p/zxing/) provide many tools for working with bar codes in java. The project does not seem to be in maven repositories, so to get started, download (http://code.google.com/p/zxing/downloads/detail?name=ZXing-1.7.zip) from their site.

Build the ‘core’ and ‘javase’ projects and put the jars into your classpath. Then create a string, use the zxing writer to encode it in a matrix, and save it to a png file:

public static void main(String[] args) {
Charset charset = Charset.forName(“ISO-8859-1”);
CharsetEncoder encoder = charset.newEncoder();
byte[] b = null;
try {
// Convert a string to ISO-8859-1 bytes in a ByteBuffer
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(“krishna”));
b = bbuf.array();
} catch (CharacterCodingException e) {
System.out.println(e.getMessage());
}

String data;
try {
data = new String(b, “ISO-8859-1”);
} catch (UnsupportedEncodingException e) {
System.out.println(e.getMessage());
}

// get a byte matrix for the data
BitMatrix matrix = null;
int h = 100;
int w = 100;
com.google.zxing.Writer writer = new QRCodeWriter();
try {
matrix = writer.encode(data,
com.google.zxing.BarcodeFormat.QR_CODE, w, h);
} catch (com.google.zxing.WriterException e) {
System.out.println(e.getMessage());
}

String filePath = “C:\temp\qr_png.png”;
File file = new File(filePath);
try {
MatrixToImageWriter.writeToFile(matrix, “PNG”, file);
System.out.println(“printing to ” + file.getAbsolutePath());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

view raw qr_code_java_sample This Gist brought to you by GitHub.

Note that the string is encoded in ISO-8859-1. A lot of barcodes don’t support unicode. The resulting QR Code png file is:

Theoretically, thousands of characters can be encoded in QR Codes, but at least one source recommended not going above 800 characters or so.

Happy coding

Bar codes aren’t just for cereal boxes any more. 2-D barcodes like Quick Response (QR) Codes are easily read by smart phones and are showing up everywhere from magazinee, restaurant fronts, advertisement, & business cards. With some of the open-source libraries out there, it’s not hard to create your own QR Codes with java.To generate…

Leave a Reply

Your email address will not be published. Required fields are marked *