welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ:9167702333 邮箱:admin@xlongwei.com

ZxingUtil 二维码接口


分类 Java   关键字 分享   标签 java   web   algorithm   发布 hongwei  1461599537577
注意 转载须保留原文链接,译文链接,作者译者等信息。  
Zxing(Zebra Crossing)支持二维码生成和识别,使用起来也比较方便。二维码容错率有4个级别(从7%至30%),即内容重复编码以便在部分被遮挡时仍能被扫码识别,因此可以支持中央放置遮挡图标而不影响二维码识别。

生成二维码,在前端可以支持图标上传,见ServiceHandlerQrcode
/** 生成size大小的二维码,并嵌入logo图标 */
public static byte[] encode(String content, int size, String logo) {
try {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, 0);
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//建议使用30%容错率,识别更快速
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size, hints);
if(StringUtil.isUrl(logo)) {
byte[] bytes = FileUtil.bytes(logo);
if(bytes != null) {
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
int x = (size-img.getWidth()) / 2, y = (size-img.getHeight()) / 2;
BufferedImage qrcode = MatrixToImageWriter.toBufferedImage(bitMatrix);
BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); //size * size,方形二维码
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.drawImage(qrcode, 0, 0, null);
g2.setBackground(Color.WHITE); //qrcode直接绘制logo效果不好,因此复制一遍
g2.clearRect(x, y, img.getWidth(), img.getHeight()); //图标区域清空二维码
g2.drawImage(img, x, y, null);
return Image.bytes(image, "png");
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", baos);
return baos.toByteArray();
}catch(Exception e) {
logger.info("fail to encode qrcode: "+e.getMessage()+", content: "+content);
return null;
}
}

识别二维码
public static String decode(byte[] encode) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(encode);
BufferedImage image = ImageIO.read(bais);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result decode = reader.decode(binaryBitmap, hints); //reader = new MultiFormatReader()
return decode.getText();
}catch(Exception e) {
logger.info("fail to decode qrcode: "+e.getMessage()+", byte length: "+encode.length);
return null;
}
}

demo地址:http://cms.xlongwei.com/demo/share.html