当前位置: 代码迷 >> Android >> Android从内部/外部存储选择图像
  详细解决方案

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

热度:8   发布时间:2023-08-04 11:15:53.0

我正在尝试将设备的内部和外部存储器中的图像添加到我的应用程序中。 我能够打开图库意图并获取文件的路径,但是随后我无法将其转换为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活动返回并返回文件的路径后,该图像不会显示在ImageView上。 变为背景色。

您可以将Uri直接设置为ImageView如下所示:

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

然后从ImageView获取位图:

 Drawable drawable =  imageView.getDrawable();
 Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
  相关解决方案