Google Zxing 二维码生成与解析

时间:2023-03-09 00:11:05
Google Zxing 二维码生成与解析

生成二维码的开源项目可谓是琳琅满目,SwetakeQRCode、BarCode4j、Zxing......

前端有JQuery-qrcode,同样能实现生成二维码。

选择Zxing的原因可能是对 Google 公司的信赖和个人崇拜吧。

其实使用起来相当的简单,我这里使用的是最新3.2 Zxing.jar ,省的你找jar的时间,下面是下载地址。

百度云盘地址:http://pan.baidu.com/s/1c0VXMPa  提取密码: bssv

生成二维码:

    public static String createQrcode(String _text){
String qrcodeFilePath = "";
try {
int qrcodeWidth = 300;
int qrcodeHeight = 300;
String qrcodeFormat = "png";
HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode('http://www.cnblogs.com/java-class/', BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints); BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
Random random = new Random();
File QrcodeFile = new File("F:\\qrcode\\" + random.nextInt() + "." + qrcodeFormat);
ImageIO.write(image, qrcodeFormat, QrcodeFile);
MatrixToImageWriter.writeToFile(bitMatrix, qrcodeFormat, QrcodeFile);
qrcodeFilePath = QrcodeFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
return qrcodeFilePath;
}

a.上述代码中的 hints,为生成二维码时的一些参数设置,实现者将它构建Map类型的参数。

b.上述生成实现当中,每生成一个二维码都会存放在目录下面,名称取整数随机数。

c. MultiFormatWriter 对象为生成二维码的核心类,后面的 MatrixToImageWriter 只是将二维码矩阵输出到图片上面。

解析二维码:

   public static String decodeQr(String filePath) {
String retStr = "";
if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) {
return "图片路径为空!";
}
try {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<>();
hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);
retStr = result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return retStr;
}

a.读取二维码图片,并送给 Zxing LuminanceSource 和 Binarizer 两兄弟的处理。

b.处理完的位图和相应的解析参数,交由 MultiFormatReader 处理,并返回解析后的结果。

c.如果对上述 两兄弟的处理 和 MultiFormatReader  的解析有兴趣,可以读读源码。