生成QR二维码图片的简单示例
QR二维码的生成,在生成QR二维条码中已经提及。不过上次是通过网站生成的,缺点是对网站的依赖。下面做了个调用zxing core实现生成QR二维码图片的示例。另外还可以通过这个办法生成其他条形码格式图形。对程序生成图片开始扫描:
扫描出结果:
在zxing的官方网站:
http://code.google.com/p/zxing没有提到生成条码图片的功能。core组件是:
The core image decoding library, and test code是图形解码库,和测试代码。
找了其他的一些java实现的条码生成图片库:
- barbecus,开源的,不过只有一维码,而且自从2007年5月以后再没有更新;
- aspose barcode,可以免费试用,不过如需去掉上面的aspose demo字样,需要购买授权。
zxing没有单独的core组件下载。需要先下载zip包,是所有项目的源代码。用ant编译core部分,得到core.jar文件即可。该组件库运行时不依赖其他类库。
我把core库上传到自己的maven repository上了,通过maven使用更方便。zxing没有提供maven库或者上传到公共库中。
源代码见:
com.google.zxing
zxing-core
1.5
http://easymorse.googlecode.com/svn/tags/barcode-demo-0.1/需要注意的是,在做QR编码的时候要增加字符集声明,这里是UTF-8,否则中文会出现乱码。
主要编码在这个方法里面:
public void generate(OutputStream outputStream) {
QRCodeWriter writer = new QRCodeWriter();
try {
ByteMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE,
width, height, hints);
byte[][] matrixByte = matrix.getArray();
BufferedImage bimg = new BufferedImage(width, height,
BufferedImage.TYPE_BYTE_GRAY);
byte[] linearbuffer = new byte[width * height];
for (int y = 0,i=0; y < height; y++) {
for (int x = 0; x < width; x++) {
linearbuffer[i++] = matrixByte[y][x];
}
}
bimg.getRaster().setDataElements(0, 0, width, height, linearbuffer);
ImageIO.write(bimg, "png", outputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
最新评论