Android 从内部/外部存储中选择图像

Adr*_*pez 2 storage android

我正在尝试将设备内部和外部存储器中的图像添加到我的应用程序中。我能够打开图库意图并获取文件的路径,但随后我无法将其转换为我的 ImageView 的位图。这是调用图库的图标的 onClick 侦听器的代码:

icoGallery = (ImageView) findViewById(R.id.icoGallery);
icoGallery.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
    }
});
Run Code Online (Sandbox Code Playgroud)

这是 onActivitResult 的代码:

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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null !=data){
        Uri selectedImageUri = data.getData();
        String[] projection = {MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
        cursor.moveToFirst();

        int column_index = cursor.getColumnIndex(projection[0]);
        imagePath = cursor.getString(column_index);
        cursor.close();

        imageFile = new File(imagePath);
        if (imageFile.exists()){
            Bitmap imageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            imgPhoto.setImageBitmap(imageBitmap);
        }

    } else {
        Toast.makeText(context, "You have not selected and image", Toast.LENGTH_SHORT).show();
    }
}
Run Code Online (Sandbox Code Playgroud)

我在清单中包含了以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)

我不断收到以下错误

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/20170215_152240.jpg: open failed: EACCES (Permission denied)
Run Code Online (Sandbox Code Playgroud)

我相信它失败的部分原因是因为该设备只有内部存储。有没有办法从本地存储或外部存储的设备添加图像?或者我是否必须制作一个功能来询问用户是要使用内部存储还是外部存储?

提前致谢 :)

编辑: 错误是由未初始化 ImageView 引起的。但是,从 Gallery Activity 返回并返回文件路径后,ImageView 上不会显示该图像。它更改为背景颜色。

Che*_*shi 5

你可以Uri直接设置为ImageViewLike this:

Uri selectedImageUri = data.getData();
imageView.setImageURI(selectedImageUri);
Run Code Online (Sandbox Code Playgroud)

然后从 ImageView 获取 Bitmap:

 Drawable drawable =  imageView.getDrawable();
 Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Run Code Online (Sandbox Code Playgroud)