I didn't know Zxing has an encoding module, which is great news. I
used to have to call Google Chart api for this purpose. I took the
liberty of enhancing Nicolai's code to create a more complete encoding
function. For those who are interested the function is below. Feel
free to use, modify and/or give feedback.
The generated code contains "the quiet zone" as described in QR code
spec (at least 4 modules on each size)
-------------------------------------------------
private static void generateQRCodeImage(OutputStream outputStream,
String code, int width, int height) throws Exception {
if (code == null || code.length() == 0)
throw new Exception("Code unspecified");
if (width <= 0 || height <= 0)
throw new Exception("Invalid width: " + width + " or height " +
height);
if (width != height)
throw new BarcodeException("width " + width + " and height " +
height + " are not the same");
QRCode qrcode = new QRCode();
Encoder.encode(code, ErrorCorrectionLevel.L, qrcode);
int qrSize = qrcode.getMatrixWidth();
int margin = 4;
int imageSize = qrSize + 2 * margin; // includes quiet zone
if (width < imageSize) width = imageSize;
int magnify = width / imageSize;
int remaining = width % imageSize;
int topLeftPosition = ((remaining > 0) ? remaining / 2 : magnify) +
margin * magnify;
int size = width;
// Make the BufferedImage that are to hold the QRCode
BufferedImage image = new BufferedImage(size, size,
BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, size, size);
// paint the image using the ByteMatrix
graphics.setColor(Color.BLACK);
for (int i = 0; i < qrSize; i ++) {
for (int j = 0; j < qrSize; j ++) {
if (
qrcode.at(i, j) == 1)
graphics.fillRect(topLeftPosition + i * magnify, topLeftPosition
+ j * magnify, magnify, magnify);
}
}
ImageIO.write(image, "png", outputStream);
}