android选取系统相册图片后,识别图中二维码

时间:2024-03-07 14:35:40

项目中添加设备操作需要扫描二维码,考虑到多种扫码方式,也添加直接识别二维码图片的操作。

首先跳转系统相册选取图片

        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, DEVICE_PHOTO_REQUEST);

接着将选取的图片展示到界面

 1 @Override
 2     public void onActivityResult(int requestCode, int resultCode, Intent data) {
 3         //用户没有进行有效的设置操作,返回
 4         if (requestCode == Activity.RESULT_CANCELED ){
 5             ToastUtil.showToast(AddDeviceActivity.this, R.string.cancel);
 6             return;
 7         }
 8         if (DEVICE_PHOTO_REQUEST == requestCode){
 9             if (null != data) {
10                 Uri selectedImage = data.getData();
11                 String[] filePathColumns = {MediaStore.Images.Media.DATA};
12                 String imagePath;
13                 Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
14                 if (c != null) {
15                     c.moveToFirst();
16                     int columnIndex = c.getColumnIndex(filePathColumns[0]);
17                     imagePath = c.getString(columnIndex);
18                     c.close();
19                     
20             Bitmap bm = BitmapFactory.decodeFile(imgPath);
21             img_code.setImageBitmap(bm);
22                 } else {
23                     ToastUtil.showToast(this, "图片路径为空");
24                 }
25             }
26         }
27         super.onActivityResult(requestCode, resultCode, data);
28     }
29     

然后用第三包的方法解码识别(需要导入\'cn.bingoogolapple:bga-zxing:1.1.9@aar\'),注意自己处理一下匿名 AsyncTask 内部类导致的Activity 泄漏问题

     img_code.setDrawingCacheEnabled(true);
        final Bitmap bmp = img_code.getDrawingCache();
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                return QRCodeDecoder.syncDecodeQRCode(bmp);
            }

            @Override
            protected void onPostExecute(String result) {
                if (TextUtils.isEmpty(result)) {
                    Toast.makeText(AddDeviceActivity.this, "二维码解析失败", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AddDeviceActivity.this, result, Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();