Android中使用Kotlin显示应用存储目录下JPEG图片的实现方法咨询
Android中使用Kotlin显示应用存储目录下JPEG图片的实现方法咨询
嗨,我完全懂你的困扰——查了好多资料都说用ImageView得把图片放到res/drawable里,但你的JPEG存在应用自己的存储目录里,还想用Kotlin实现,不想折腾复制文件的操作对吧?别担心,完全不需要非要把图片移到drawable目录,下面就给你说两种直接加载应用存储目录图片的实用方法:
方法一:用BitmapFactory直接解码文件路径
这种方法适合快速加载,直接从文件路径生成Bitmap然后设置给ImageView:
// 替换成你的图片实际所在的应用存储目录路径,这里示例是应用外部私有目录 val imageFile = File(getExternalFilesDir(null), "target_image.jpg") if (imageFile.exists()) { // 解码文件生成Bitmap val bitmap = BitmapFactory.decodeFile(imageFile.absolutePath) // 给ImageView设置Bitmap your_target_image_view.setImageBitmap(bitmap) }
注意:getExternalFilesDir(null)获取的是应用的外部私有存储目录,在Android 10及以上版本,访问这个目录不需要申请额外的存储权限;如果你的图片在其他目录,可能需要根据系统版本申请对应的存储权限哦。
方法二:用FileProvider生成安全Uri加载(适配Android 7.0+)
Android 7.0及以上版本禁止直接使用file://格式的Uri暴露给应用组件,否则会抛出FileUriExposedException,这时候就需要用FileProvider来生成安全的content://格式Uri:
第一步:配置FileProvider
- 在
AndroidManifest.xml中添加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>
- 在
res/xml目录下创建file_paths.xml文件(如果没有xml目录就新建一个),配置要共享的文件路径:
<paths xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 这里配置你图片所在的目录,示例是应用外部私有目录的根目录 --> <external-files-path name="app_images" path="." /> </paths>
第二步:Kotlin代码加载图片
val imageFile = File(getExternalFilesDir(null), "target_image.jpg") if (imageFile.exists()) { // 生成安全的content格式Uri val imageUri = FileProvider.getUriForFile( this, "${packageName}.fileprovider", // 这里和Manifest里的authorities保持一致 imageFile ) // 给ImageView设置Uri your_target_image_view.setImageURI(imageUri) }
这两种方法都能帮你直接加载应用存储目录里的JPEG图片,不用再费劲把文件复制到res/drawable里啦~
内容来源于stack exchange
相关产品推荐
相关产品推荐

