android跳到系统相册选择图片并根据uri获取真实图片路径

1.首先跳转到系统相册选择图片
public void ChoosePicture(View view)
    {
        // 激活系统图库,选择一张图片
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 0);
    }
2.重载startActivityForResult函数,处理所选择的图片
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if( requestCode == 0)
        {
            if( data != null )
            {
                Bitmap bitmapLocal = null;
                Uri uri = data.getData(); //获取图片uri
                String imagePath = getRealPathFromURI(uri); // 根据URI找到图片真正的路径
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                bitmapLocal = BitmapFactory.decodeFile(imagePath, options); 
                this.image.setImageBitmap(bitmapLocal);
                this.bitmap = bitmapLocal;
                super.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

其中,getRealPathFromURI函数将文件的uri转化为文件路径,具体代码如下:

private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        //不能直接调用contentprovider的接口函数,需要使用contentresolver对象,通过URI间接调用contentprovider
        if (cursor == null) {
            // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

到这里我们就成功将获取到图片的文件路径啦。

你可能感兴趣的:(android跳到系统相册选择图片并根据uri获取真实图片路径)