安卓扫描相册二维码

1.获取读相册,读取sd卡的权限。

2.打开相册选择二维码照片。

3.获取选中图片的路径,对图片内容进行解析。

if(ContextCompat.checkSelfPermission(CustomCaptureActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
    ActivityCompat.requestPermissions(CustomCaptureActivity.this,new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE},1);
}else {
   openPhoto();
   }
        
   

获取权限成功打开相机,如果权限没有打开。去获取。

 if(grantResults.length>0 &&grantResults[0]==PackageManager.PERMISSION_GRANTED){
     openPhoto();
 }else{
     Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
}

权限申请完毕,打开相册,选择照片。

 private void openPhoto(){
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

接下来重写onActivityResult方法,获取结果。

String path ="";
String[] proj = { MediaStore.Images.Media.DATA };
// 获取选中图片的路径
Cursor cursor = getContentResolver().query(data.getData(),proj, null, null, null);
if (cursor != null) {
    cursor.moveToFirst();
    path = cursor.getString(cursor.getColumnIndexOrThrow(proj[0]));
}
cursor.close();
Result result = scanningImage(path);
Toast.makeText(this,result.toString(),Toast.LENGTH_SHORT).show();
protected Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        // DecodeHintType 和EncodeHintType
        Hashtable hints = new Hashtable();
        // 设置二维码内容的编码
        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
        BitmapFactory.Options options = new BitmapFactory.Options();
        // 先获取原大小
        options.inJustDecodeBounds = true;
        Bitmap scanBitmap ;
        // 获取新的大小
        options.inJustDecodeBounds = false;
        int sampleSize = (int) (options.outHeight / (float) 200);
        if (sampleSize <= 0){
            sampleSize = 1;
        }
        options.inSampleSize = sampleSize;
        scanBitmap = BitmapFactory.decodeFile(path, options);
        int[] data = new int[scanBitmap.getWidth() * scanBitmap.getHeight()];
        scanBitmap.getPixels(data, 0, scanBitmap.getWidth(), 0, 0, scanBitmap.getWidth(), scanBitmap.getHeight());
        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap.getWidth(),scanBitmap.getHeight(),data);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        try {
            return reader.decode(bitmap1, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }

        return null;

    }

目前这部分只能识别二维码直接保存的图片,不能识别一张包含二维码的照片。

你可能感兴趣的:(安卓扫描相册二维码)