使用zxing解析二维码抛出com.google.zxing.NotFoundException 解决方案
普通的二维码解析的时候,没什么问题。当二维码复杂了,或者是中间有LOGO的时候就报错,而且错误还看不出来具体错误信息,就一个com.google.zxing.NotFoundException,感觉这个处理的有点恶心。
搜索了一些资料不是我的解决的方案,不过也罗列一下:
1.二维码所有bit都是0,然后分析了一下,发现我在生成二维码的时候白色像素填充使用的是透明色,这样在显示的时候因为背景是白色,所以看上去和用手机扫都没有问题,但是自己代码识别的时候就会把透明色识别为黑色,这样就导致整个二维码图片全是黑色像素,所以zxing抛出com.google.zxing.NotFoundException异常。
2.乱码。
// 解码设置编码方式为:utf-8,
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
3.优化精度。
//优化精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
4.开启PURE_BARCODE模式。(这是解决我的方案,带图片LOGO的解码方案)
//复杂模式,开启PURE_BARCODE模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
第四个方案,是解决我的问题的方案,你们可以试试。
附上我的解码代码源码。
/**
* 流图片解码
* @param input
* @return QRResult
*/
public static QRResult decode(InputStream input) {
BufferedImage image;
try {
if (null == input) {
return new QRResult("得到的文件不存在!",300);
}
image = ImageIO.read(input);
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Map<DecodeHintType,Object> hints = new LinkedHashMap<DecodeHintType,Object>();
// 解码设置编码方式为:utf-8,
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
//优化精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//复杂模式,开启PURE_BARCODE模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
Result result = new MultiFormatReader().decode(bitmap, hints);
String txt = result.getText();
return new QRResult("成功解码!",200,txt);
} catch (Exception e) {
LoggerUtils.error(MatrixUtil.class,"解码失败。", e);
return new QRResult("解码失败,请确认的你二维码是否正确,或者图片有多个二维码!",500);
}
}
/**
* 返回值处理
* @author zhou-baicheng
*
*/
public static class QRResult{
public QRResult(String message,int status) {
this.message = message;
this.status = status;
this.txt = "";
}
public QRResult(String message,int status,String txt) {
this.message = message;
this.status = status;
this.txt = txt;
}
//解码内容
private String txt;
//返回的消息内容
private String message;
//返回的状态码,200:成功,500:错误
private int status ;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
}
版权所属:SO JSON在线解析
原文地址:https://www.sojson.com/blog/183.html
转载时必须以链接形式注明原始出处及本声明。
如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。