您的位置:首页 > 编程语言 > Java开发

Java利用Zxing生成二维码

2014-10-13 11:01 405 查看
Zxing是Google提供的关于条码(一维码、二维码)的解析工具,提供了二维码的生成与解析的方法,现在我简单介绍一下使用Java利用Zxing生成与解析二维码

1、二维码的生成

  1.1 将Zxing-core.jar 包加入到classpath下。

   1.2 二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类拷贝到源码中,这里我将该类的源码贴上,可以直接使用。

// generate qrcode
public BitMatrix generateQrcode(String content,int width, int height){
Map hints = new HashMap<EncodeHintType, Object>;
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix matrix = new MultiFormatWriter.encode(content,BarcodeFormat.QR_CODE, width, height, hintMap);
return matrix;
}
BitMatrix类里有一个int[]bits,说明Qrcode内容的本质是用一个二进制数(011100101),1表示true,代表黑色,0表示false,代表白色.

// write to outputStream
public String writeToFile(BitMatrix matrix, String type) {
BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ImageIO.write(image, type, byteOut);
// get base64Image
byte[] byteImage = byteOut.toByteArray();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
return encoder.encode(byteImage);
}


// write to file
public void writeToFile(BitMatrix matrix, String filePath) {
BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);
ImageIO.write(image, "jpg", new File(filePath));
}


2、二维码的解析

  2.1 将Zxing-core.jar 包加入到classpath下。  

  2.2 和生成一样,我们需要一个辅助类( BufferedImageLuminanceSource),同样该类Google也提供了. 编写解析二维码的实现代码.

try {
MultiFormatReader formatReader = new MultiFormatReader();
String filePath = "C:/Users/Administrator/Desktop/testImage/test.jpg";
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);;
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer  binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
Result result = formatReader.decode(binaryBitmap,hints);

System.out.println("result = "+ result.toString());
System.out.println("resultFormat = "+ result.getBarcodeFormat());
System.out.println("resultText = "+ result.getText());

} catch (Exception e) {
e.printStackTrace();
}


learn from :http://www.cnblogs.com/jtmjx/archive/2012/06/18/2545209.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: