使用zxing解析相册图片是发现只能解析黑白的图片,后面又试了微信和qq都能成功解析了彩色的图片,网上找了半天没找到办法,最后在github上找到了解决方法
下面的方法只能解析黑白的二维码
/**
* 解析二维码图片
*/
public static String decodeQRCode(Bitmap srcBitmap) {
MultiFormatReader multiFormatReader = new MultiFormatReader();
// 解码的参数
Hashtable<DecodeHintType, Object> hints = new Hashtable<>(2);
// 可以解析的编码类型
Vector<BarcodeFormat> decodeFormats = new Vector<>();
if (decodeFormats == null || decodeFormats.isEmpty()) {
// 设置可扫描的类型
decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
}
hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
multiFormatReader.setHints(hints);
Result result = null;
BitmapLuminanceSource source = new BitmapLuminanceSource(srcBitmap);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
result = multiFormatReader.decodeWithState(binaryBitmap);
} catch (Exception e) {
e.printStackTrace();
}
if (result != null) {
return result.getText();
}
return null;
}
支持彩色二维码解析
/**
* 解析图片
*
* @param srcBitmap
* @return
*/
public static String decodeQRCode(Bitmap srcBitmap) {
// 解码的参数
Hashtable<DecodeHintType, Object> hints = new Hashtable<>(2);
// 可以解析的编码类型
Vector<BarcodeFormat> decodeFormats = new Vector<>();
if (decodeFormats.isEmpty()) {
decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
}
hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = null;
int width = srcBitmap.getWidth();
int height = srcBitmap.getHeight();
int[] pixels = new int[width * height];
srcBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
//新建一个RGBLuminanceSource对象
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
//将图片转换成二进制图片
BinaryBitmap binaryBitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
QRCodeReader reader = new QRCodeReader();//初始化解析对象
try {
result = reader.decode(binaryBitmap, hints);//开始解析
} catch (NotFoundException | ChecksumException | FormatException e) {
e.printStackTrace();
}
if (result != null) {
return result.getText();
}
return null;
}