美文网首页
Android zxing解析彩色的二维码图片

Android zxing解析彩色的二维码图片

作者: 假装很正经_e60e | 来源:发表于2018-09-25 17:46 被阅读0次

使用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;
    }

相关文章

网友评论

      本文标题:Android zxing解析彩色的二维码图片

      本文链接:https://www.haomeiwen.com/subject/rkiloftx.html