java - 如何正确设置用户选择的文件夹中图像的 Uri 以在 ImageView 中显示?

标签 java android bitmap imageview uri

我需要显示一张图像,我知道文件名但不知道文件夹,必须由用户指定。

我使用 Intent Intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); 从用户处获取文件夹。它返回一个带有如下路径的 Uri:

content://com.android.externalstorage.documents/tree/primary%3ADownload

现在我需要在 ImageView 中显示此文件夹中的图像。我尝试了以下方法:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), 
Uri.parse(chosenFolder + "/image.png"));
ImageView imageView = findViewById(R.id.imageview);
imageView.setImageBitmap(bitmap);

第一行抛出以下异常:

java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/primary%3ADownload/image.png

: 替换 %3A 不起作用。

如何正确设置显示图片的Uri?

最佳答案

我认为你应该使用文件路径而不是URIcontent:// Uri 不必代表文件系统上的文件。

试试这个:

String filePath = null;
if (chosenFolder != null && "content".equals(chosenFolder.getScheme())) {
    Cursor cursor = this.getContentResolver().query(chosenFolder, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
    cursor.moveToFirst();   
    filePath = cursor.getString(0);
    cursor.close();
} else {
    filePath = chosenFolder.getPath();
}

然后使用文件路径创建位图:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), 
Uri.parse(filepath+ "/image.png"));

关于java - 如何正确设置用户选择的文件夹中图像的 Uri 以在 ImageView 中显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56388225/

相关文章:

java - Hibernate, MySQL - 数据截断 : Data too long for column exception message

android - 如何绘制局部位图圆弧?就像一个圆形进度轮,但带有越来越多显示的位图。

android - Android 的 ImageCache 应该使用 Bitmap 还是 Drawable 存储?

java - 回收器 View : No adapter attached; skipping layout (no shw Slider and photos Picasso and Sliderbanner

java - 从文本中提取特定单词

java - 如何使用锁包装器进行自动关闭?

android - "You need to add at least 2 non-Android TV screenshots"

android - 您可以作为 Google 开发者销售应用程序还是必须是商家?

java - 关于 isConnectingOrConnecting 的替代编码?

android - 位图总是显示为空?