Android从图库选择照片并获取图片的path

在一个项目中难免要去获取本机图片。比如qq发表说说插入图片需要进入图库加载图片、设置一张壁纸也要进入图库选择图片…所以现在我们来实现这个功能

1.既然是进入系统应用,那肯定少不了万能的Intent

/** *以带结果的方式启动Intent,这样就可以拿到图片地址 */
 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        intent.putExtra("crop", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 0);

2.重写onActivityResult获取图片地址(获取uri)

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //uri代表的就是图片在内容解析者所在的地址
        if (requestCode == 0) {
            Uri uri = data.getData();
            ContentResolver cr = context.getContentResolver();
            try {
                Bitmap bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

3.重写onActivityResult获取图片地址(获取绝对路径)

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0) {
           Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            //picturePath就是图片在储存卡所在的位置
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
        }
    }

点我有惊喜哦

你可能感兴趣的:(android,图片,Path,图库)