生成二维码的开源项目可谓是琳琅满目,SwetakeQRCode、BarCode4j、Zxing......前端
前端有JQuery-qrcode,一样能实现生成二维码。java
选择Zxing的缘由多是对 Google 公司的信赖和我的崇拜吧。dom
其实使用起来至关的简单,我这里使用的是最新3.2 Zxing.jar ,省的你找jar的时间,下面是下载地址。spa
百度云盘地址:http://pan.baidu.com/s/1c0VXMPa 提取密码: bssvcode
生成二维码:orm
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.上述生成实现当中,每生成一个二维码都会存放在目录下面,名称取整数随机数。blog
c. MultiFormatWriter 对象为生成二维码的核心类,后面的 MatrixToImageWriter 只是将二维码矩阵输出到图片上面。图片
解析二维码:get
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 的解析有兴趣,能够读读源码。