使用zxing解析相冊(cè)圖片是發(fā)現(xiàn)只能解析黑白的圖片捍壤,后面又試了微信和qq都能成功解析了彩色的圖片室埋,網(wǎng)上找了半天沒找到辦法辖试,最后在github上找到了解決方法
下面的方法只能解析黑白的二維碼
/**
* 解析二維碼圖片
*/
public static String decodeQRCode(Bitmap srcBitmap) {
MultiFormatReader multiFormatReader = new MultiFormatReader();
// 解碼的參數(shù)
Hashtable<DecodeHintType, Object> hints = new Hashtable<>(2);
// 可以解析的編碼類型
Vector<BarcodeFormat> decodeFormats = new Vector<>();
if (decodeFormats == null || decodeFormats.isEmpty()) {
// 設(shè)置可掃描的類型
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) {
// 解碼的參數(shù)
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);
//新建一個(gè)RGBLuminanceSource對(duì)象
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
//將圖片轉(zhuǎn)換成二進(jìn)制圖片
BinaryBitmap binaryBitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
QRCodeReader reader = new QRCodeReader();//初始化解析對(duì)象
try {
result = reader.decode(binaryBitmap, hints);//開始解析
} catch (NotFoundException | ChecksumException | FormatException e) {
e.printStackTrace();
}
if (result != null) {
return result.getText();
}
return null;
}