Thursday, 14 February 2013

How to create QR Codes in Java

How to create QR Codes in Java
Posted on January 13, 2011 by tborthwick

Bar codes aren't just for cereal boxes any more. 2-D barcodes like QR Codes are easily read by smart phones and are showing up everywhere from magazines to restaurant fronts to 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, there are several online generators, like this. Here is a link to this site:

Urls, contacts, calendar events, even wifi network info are getting put into QR Codes. But you don't have to stick to standard content or to provided generators. So how would you encode 'hello world' in a QR Code?

The good folks working on 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 ZXing-1.6.zip from their site. I didn't notice any built jars in there, but it's easy to build from the source with ant or maven (build.xml and pom.xml files are provided).

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("hello world"));
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());
}
}

No comments: