java generate QR code with ZXing

Download ZXing 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) {
    String data;
    try {
        data = new String(b, “ISO-8859-1”);
    } catch (UnsupportedEncodingException e) {
    // get a byte matrix for the data
    BitMatrix matrix = null;
    int h = 100;
    int w = 100; writer = new QRCodeWriter();
    try {
        matrix = writer.encode(data,, w, h);
    } catch ( e) {
    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) {
Theoretically, thousands of characters can be encoded in QR Codes, but at least one source recommended not going above 800 characters or so.

One comment

  1. Andy Res · June 30, 2012

    Cool! From their google code page it seem they support Android too.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s