You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过URI从样本目录images加载11.png到ImageView

加载images目录下11.png到ImageView的实现方案

首先得明确你的images目录具体放在哪里——不同的存储位置,路径写法和注意事项都不一样,我分几种常见情况给你说明:

情况1:images目录在应用内部存储的files文件夹下

这是应用私有的存储目录,不需要申请额外权限,路径可以这么写:

// 获取应用内部files目录的路径
String internalImagesPath = getFilesDir() + "/images/11.png";
File imageFile = new File(internalImagesPath);
if (imageFile.exists()) {
    imageView.setImageURI(Uri.fromFile(imageFile));
} else {
    // 处理文件不存在的情况,比如显示占位图
}

情况2:images目录在外部存储的公共目录(比如Pictures文件夹下)

这种属于公共存储,不同Android版本的访问规则有差异:

Android 9及以下

需要在Manifest里声明READ_EXTERNAL_STORAGE权限,并且在运行时动态申请,路径写法:

// 获取公共Pictures目录下的images文件夹路径
String externalImagesPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/images/11.png";
File imageFile = new File(externalImagesPath);
if (imageFile.exists()) {
    imageView.setImageURI(Uri.fromFile(imageFile));
}

Android 10及以上

直接用file:// URI会触发FileUriExposedException,而且不能直接访问公共目录的文件路径,推荐用FileProvider生成content URI:

  1. 先在Manifest里注册FileProvider:
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
  1. 在res/xml目录下创建file_paths.xml,配置外部存储路径:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_images" path="Pictures/images/" />
</paths>
  1. 生成URI并设置到ImageView:
File imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "images/11.png");
if (imageFile.exists()) {
    Uri imageUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", imageFile);
    imageView.setImageURI(imageUri);
}

情况3:images目录在assets文件夹下

注意:assets里的文件不属于设备的文件系统,Uri.fromFile()无法直接使用,得通过AssetManager加载:

try {
    InputStream is = getAssets().open("images/11.png");
    Bitmap bitmap = BitmapFactory.decodeStream(is);
    imageView.setImageBitmap(bitmap);
    is.close();
} catch (IOException e) {
    e.printStackTrace();
}

最后提醒:不管哪种场景,都要先判断文件是否存在,避免加载失败或抛出异常。

内容的提问来源于stack exchange,提问作者Olimjon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:25:14