解析二维码

implementation'com.google.zxing:core:3.3.0' //库

使用如下:

try{

Result ss = parsePic(bitmap);//解析二维码

    Log.i("erwe", ss.getText().toString() +"");

}catch (Exception e){

e.printStackTrace();

}

public ResultparsePic(Bitmap bitmaps) { //解析函数

//解析转换类型UTF-8

    Hashtable hints =new Hashtable();

    hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

    //新建一个RGBLuminanceSource对象,将bitmap图片传给此对象

    RGBLuminanceSource rgbLuminanceSource =new RGBLuminanceSource(bitmaps);

    //将图片转换成二进制图片

    BinaryBitmap binaryBitmap =new BinaryBitmap(new HybridBinarizer(rgbLuminanceSource));

    //初始化解析对象

    QRCodeReader reader =new QRCodeReader();

    //开始解析

    Result result =null;

    try {

result = reader.decode(binaryBitmap, hints);

    }catch (Exception e) {

e.printStackTrace();

    }

return result;

}

public class RGBLuminanceSourceextends LuminanceSource {

private byte bitmapPixels[];

    protected RGBLuminanceSource(Bitmap bitmap) {

super(bitmap.getWidth(), bitmap.getHeight());

        // 首先,要取得该图片的像素数组内容

        int[] data =new int[bitmap.getWidth() * bitmap.getHeight()];

        this.bitmapPixels =new byte[bitmap.getWidth() * bitmap.getHeight()];

        bitmap.getPixels(data, 0, getWidth(), 0, 0, getWidth(), getHeight());

        // 将int数组转换为byte数组,也就是取像素值中蓝色值部分作为辨析内容

        for (int i =0; i < data.length; i++) {

this.bitmapPixels[i] = (byte) data[i];

        }

}

@Override

    public byte[]getMatrix() {

// 返回我们生成好的像素数据

        return bitmapPixels;

    }

@Override

    public byte[]getRow(int y, byte[] row) {

// 这里要得到指定行的像素数据

        System.arraycopy(bitmapPixels, y * getWidth(), row, 0, getWidth());

        return row;

    }

}

你可能感兴趣的:(解析二维码)