Android----识别图片二维码

导入包

compile 'com.google.zxing:core:3.2.1'
compile 'cn.bingoogolapple:bga-qrcodecore:1.1.7@aar'
compile 'cn.bingoogolapple:bga-zxing:1.1.7@aar'

使用代码

String path = getIntent().getStringExtra("path");//文件路径
result = QRHelper.getReult(BitmapFactory.decodeFile(path));

工具类


public class QRHelper {
 
    public static String getReult(Bitmap mBitmap) {
        String string = null;
        if (mBitmap != null) {
            string = scanBitmap(mBitmap);
        }
        if (!TextUtils.isEmpty(string)) {
            return string;
        }
        return null;
    }
 
    private static String scanBitmap(Bitmap mBitmap) {
        Result result = scan(mBitmap);
        if (result != null) {
            return recode(result.toString());
        } else {
            return null;
        }
    }
 
    private static String recode(String str) {
        String formart = "";
        try {
            boolean ISO = Charset.forName("ISO-8859-1").newEncoder()
                    .canEncode(str);
            if (ISO) {
                formart = new String(str.getBytes("ISO-8859-1"), "GB2312");
            } else {
                formart = str;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return formart;
    }
 
    private static Result scan(Bitmap mBitmap) {
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 设置二维码内容的编码
        Bitmap scanBitmap = Bitmap.createBitmap(mBitmap);
 
        int px[] = new int[scanBitmap.getWidth() * scanBitmap.getHeight()];
        scanBitmap.getPixels(px, 0, scanBitmap.getWidth(), 0, 0,
                scanBitmap.getWidth(), scanBitmap.getHeight());
        RGBLuminanceSource source = new RGBLuminanceSource(
                scanBitmap.getWidth(), scanBitmap.getHeight(), px);
        BinaryBitmap tempBitmap = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        try {
            return reader.decode(tempBitmap, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
        return null;
    }
}

你可能感兴趣的:(Android----识别图片二维码)