Android select 来自内部/外部存储的图像

Android select image from internal / external storage

我正在尝试将设备的内部和外部存储器中的图像添加到我的应用程序中。我能够打开图库意图并获取文件的路径,但是我无法将它转换为我的 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);
    }
});

这是 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();
    }
}

我已将以下权限添加到清单中:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

我不断收到以下错误

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

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

提前致谢:)

编辑: 该错误是由于未初始化 ImageView 而导致的。但是,从Gallery activity 返回并返回文件路径后,图像并没有显示在ImageView 上。它更改为背景颜色。

你可以将Uri直接设置为ImageView,像这样:

Uri selectedImageUri = data.getData();
imageView.setImageURI(selectedImageUri);

然后从ImageView获取Bitmap:

 Drawable drawable =  imageView.getDrawable();
 Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();