首页 > 解决方案 > 使用意图在图库中查看图像时不支持图像

问题描述

我想从我的应用程序打开存储在图库中本地存储中的图像。但它总是显示图像不受支持。

这是代码:

File fileStr = new File (Environment.getExternalStorageDirectory() + "/Storifier/test.jpg");
Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", fileStr);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/jpg");
startActivity(intent);

我为文件获取的 Uri 是

content://com.purple.myapplication.provider/external_files/Storifier/test.jpg

图像存储在存储中的 Storifier 文件夹中

我是新手!

标签: androiduri

解决方案


试试这个代码

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);

将此添加到您的活动结果中

@Override
    protected void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);


        if (resultCode == RESULT_OK) {
            try {
                final Uri imageUri = data.getData();
                final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                image_view.setImageBitmap(selectedImage);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(PostImage.this, "Something went wrong", Toast.LENGTH_LONG).show();
            }

        }else {
            Toast.makeText(PostImage.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
        }
    }

并将其添加到 manifest.xml

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

推荐阅读