使用ZXing进行二维码的生成

分类:.Net知识问答| 发布:camnprbubuol| 查看: | 发表时间:2011/11/17

ZXing是一个开源Java类库用于解析多种格式的1D/2D条形码。目标是能够对QR编码、Data Matrix、UPC的1D条形码进行解码。于此同时,它同样提供 cpp,ActionScript,android,iPhone,rim,j2me,j2se,jruby,C#等方式的类库。zxing类库的作用主 要是解码,是目前开源类库中解码能力比较强的(商业的另说,不过对于动辄成千上万的类库授权费用,的确很值)。

由于工作需要,需要进行二维码QR的生成和解码工作,首先是进行编码,即使用zxing类库对需要编码的字符或字节进行编码成QR码,并把这些编码 出的内容变成图片(一般是png格式)。

首先,到zxing的项目首页下载类库的完整包。解压缩后会出现如下诸多目录:

  1. core: The core image decoding library, and test code 主要用来做测试和一些演示代码,大部分为解 码测试。
  2. javase: J2SE-specific client code 有一个GUI形式的解码器代码
  3. android: Android client, called Barcode Scanner. For Google的android系统代码,内容较 多,需要引入android的SDK
  4. androidtest: Android test app 测试代码和应用示例
  5. android-integration: Supports integration with our Barcode Scanner app via Intent
  6. zxingorg: The source behind zxing.org/w ,zxing.rog的网站代码
  7. zxing.appspot.com: The source behind our web-based barcode generator, zxing.appspot.com网站代码,可以用来参考做web方式的编码生成器,不过它使用的是Google Chart Tools做的生成工具,据我测试,Google Chart Tools对中文无法生成(可能有出入,未进行深入实验)

虽然,Google Chart Tools已经可以很方便的生成QR码,不过受局限性较大,并且目前国内的防火墙经常处于不稳定时期,说不定何时chart就无法访问了。同时,生成速度 上也会受网络局限,生成器也必须联网工作,故还是自己写一个生成应用较为稳妥。

我们可以 有两种方式来生成QR码,一种复杂一种相对简单,我的研究步骤是由复杂至简单。

方法1:

我们最先看到的应该是com.google.zxing.qrcode包和com.google.zxing.qrcode.encoder包,通过查看 com.google.zxing.qrcode.encoder包的源码我们可以了解到encoder包是用来把我们提供的一系列字符编码成为二维码的 矩阵形式,并且可以由我们打印出来。有此,我们可以用它生成的矩阵,来使用java.awt类库生成图像的方式生成QR码图像。(不要想着zxing会向 目前收费类库一样,你提供字符,它生成图片那样傻瓜式,不过第二种方法对于这种傻瓜式的调用有过之而无不及。)

代码如下,这个代码对生成的图片会有问题,会造成解码器无法解码的情况,之所以我未继续进行修改是因为我发现了第二种方法:

//生成的字符型二维码有误,待调整

public class TestEncode {

public static void main(String[] args) throws Exception {
String str = “test”;//二维码内容
QRCode qrcode = new QRCode();
try {
Encoder.encode(str, ErrorCorrectionLevel.H, qrcode);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int magnify = 1; //QR码放大倍数,默认高宽为21px
byte[][] matrix = qrcode.getMatrix().getArray();
int size = qrcode.getMatrixWidth()*magnify;
//打印一下二维码
//                ByteMatrix byteMatrix = qrcode.getMatrix();
//                byte[][] bArray = byteMatrix.getArray();
//                for (int i = 0; i < bArray.length; i++) {
//                        for (int j = 0; j < bArray[i].length; j++) {
//                                System.out.print(bArray[i][j] + ” “);
//                        }
//                        System.out.println(“”);
//                }

//Make the BufferedImage that are to hold the QRCode 
BufferedImage im = new BufferedImage (size,size,BufferedImage.TYPE_INT_RGB);
im.createGraphics();
Graphics2D g = (Graphics2D)im.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, size, size);

//BitMatrix for validation
BitMatrix bm = new BitMatrix(qrcode.getMatrixWidth());

//paint the image using the ByteMatrik
for(int h = 0;h<qrcode.getMatrixWidth();h++){
for(int w = 0;w<qrcode.getMatrixWidth();w++){
//Find the colour of the dot
if(matrix[h][w] == 0)
g.setColor(Color.WHITE);
else{
g.setColor(Color.BLACK);
bm.set(h, w);//build the BitMatrix
}

//Paint the dot
g.fillRect(h*magnify, w*magnify, magnify, magnify);
}
}

//Try to decode the BitMatrix
Decoder decoder = new Decoder();
DecoderResult result = null;
try {
result = decoder.decode(bm);
} catch (ReaderException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

//Compare the decoded BitMatrix with the input string

if(!result.getText().equals(str))
throw new Exception(“Error encodeing the QRCode”);

//保存图像文件
try {
ImageIO.write(im, “png”, new File(“d:/testimg.png”));
} catch (IOException e) {
e.printStackTrace();
}
}
}

方法2:

我在zxing的诸多类库包中查找的过程中发现com.google.zxing.client.j2se类库中的MatrixToImageWriter类很是符合上面我们写的图片生成过程的口味,于是导入后试用发现原来 zxing的生成QR码竟然如此简单。

代码如下:

public class MyTestEncode {

public static void main(String[] args) {

String str = “test”;//二维码内容
String path = “d:/test”;

ByteMatrix byteMatrix;
try {
byteMatrix = new MultiFormatWriter().encode
(str,BarcodeFormat.QR_CODE, 200, 200);

File file = new File(path + “.png”); 
MatrixToImageWriter.writeToFile(byteMatrix, “png”, file);
} catch (IOException e) {
e.printStackTrace();
} catch (WriterException e1) {
e1.printStackTrace();
}
}
}

由于zxing包括很多支持各种语言和开发环境的类库,所以对于zxing的使用方法没有更加详细的阐述,只是给了我们api文档查询,当我们了解 它熟悉它以后才会发觉原来zxing用起来竟然如此舒服。

同时,zxing的core部分为代码的测试部分,在测试时需要使用到junit,用eclipse导入后,右键你想运行的方法名run as junit即可。

目前工作只涉及到编码部分,相应的解码部分的编写,以后涉及的时候我会写出。以上部分代码,参考、提取自zxing group(由 于墙的不稳定,这个地址不容易访问).

本人编程菜鸟,抛砖引玉,希望以上文字能够帮助需要的人。

来源:http://hi.baidu.com/baid/blog/item/fd446e06d199a77702088102.html
365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/net-wiki/499.html