Android - 从 uri 加载照片

Android - load photo from uri

我正在尝试通过 Uri 将图像上传到 imageview 但它不起作用。

java.io.FileNotFoundException: /file:/data/user/0/com.maksu.aquarium/cache/cropped6681458112782885202.jpg (No such file or directory)

我收到上述错误。当我检查时,我看到图片存在。

这是我上传照片的方式:

     Uri profileUri = Uri.fromFile(new File("file:///data/user/0/com.maksu.aquarium/cache/cropped6681458112782885202.jpg"));

Glide.with(this).load(profileUri).into(akvaryumDialogResim);

首先,永远不要对路径进行硬编码。出于此答案的目的,我将坚持您的硬编码值,但您确实需要一种更好的方式来处理您的文件。例如,您的硬编码路径对于很多用户来说都是错误的。

其次,file:///data/user/0/com.maksu.aquarium/cache/cropped6681458112782885202.jpg 不是文件系统路径。是一个Uri。 Android 基于 Linux,其文件系统路径以 / 开头。 file:// 是一个 Uri 方案,很像 https:// 是一个 Uri 方案用于此网页的 URL。

所以,要么使用:

Uri profileUri = Uri.parse("file:///data/user/0/com.maksu.aquarium/cache/cropped6681458112782885202.jpg");

或使用:

Uri profileUri = Uri.fromFile(new File("/data/user/0/com.maksu.aquarium/cache/cropped6681458112782885202.jpg"));

要访问缓存文件夹中的文件,您可以使用 Context.getCacheDir() 方法而不是硬编码完整路径。所以,试试:

Uri profileUri = Uri.fromFile(new File(geCacheDir(), "cropped6681458112782885202.jpg"));

Glide.with(this).load(profileUri).into(akvaryumDialogResim);