Android 从图库中存储和加载图像

Android store and load Image from gallery

我目前允许我的用户从图库中选择一张图片,然后将其加载到 ImageView 中。然后我将图像的 URI 存储在我的 sharedPreferences 中,以便以后能够再次加载它。

它不会工作,我注意到图片的 URI 不知何故发生了变化。

我想知道如何简单地存储我从图库中获得的图像以便以后能够重新加载它。

最好将图片路径存储在共享首选项中,然后重新加载

Then I store in my sharedPreferences the URI of the image in order to be able to load it again later.

那是行不通的。不仅 Uri 可能不同,而且如果 Uri 有一个 content 方案,您将在流程结束后失去使用 Uri 标识的内容的权利。另外,用户可能会删除图像。

I was wondering how to simply store the Image I got from the gallery to be able to reload it later.

使用 Java I/O 将图像复制到您控制的文件中(例如,在 internal storage 上),然后使用该副本。调整你的 UI 以反映这一点(例如,使用像 "import" 这样的动词而不是 "link")。

根据您获得 Uri 的方式,您可以致电 takePersistableUriPermission() 尝试获得内容的长期权利,在这种情况下 Uri 也应该是稳定的(假设用户没有移动或删除有问题的内容)。