android - Android - overwrite photo in photo library
问题描述
In my application I want to give users ability to open, edit and save image from Android photo library. Opening is easy, as well as saving as a new file. The problem is with overwriting images (opened from the photo library).
When saving changes I simply overwrite files, knowing the path of the original file. If user saves a brand new file (not opened from library, but created in the app), the file is saved in Android.OS.Environment.DirectoryPictures folder. (e.g. /storage/emulated/0/Pictures/img_2019921_212552.jpg) I generate random file name, append to the directory path, save, and the file is there. Knowing this path I can later update file contents by simply overwriting the file.
If however, I open a file from the photo library (including also these files that I had just created with the app), the path that is visible to me is a kind of weird (e.g. /document/image:87799). I am able to get file contents using this pseudo-code:
Android.Net.Uri uri = intent.Data;
Stream stream = ContentResolver.OpenInputStream(uri);
Upon saving however, the only thing with regard to the photo location that I have is this strange path (e.g. /document/image:87799) which of course cannot be used to open write stream to the file.
What I need is: a way to resolve this strange path into a kind of physical one, which will work with streams (to overwrite file). Or maybe I'm doing it the wrong way...? Updating image from photo library seems to be a standard task, which may have a dedicated APIs / good practices ?
解决方案
经过我的验证,CommonsWare 建议:以下代码可用于将更改的图像保存到照片库。
var uri = Android.Net.Uri.Parse(currentPhotoURL);
using (var stream = contentResolver.OpenOutputStream(uri))
{
await stream.WriteAsync(data, 0, data.Length);
}
重要的是,这里没有使用文件系统 API。
现在,由于解决了覆盖现有文件的问题(知道原始图像的 URI),我如何在不使用文件系统 API 的情况下编写全新的图像(字节 [] 数组,例如使用编码的 jpeg)?(这是我目前为“另存为新文件”操作所做的)。最终,我将需要图像的 URI(以 content:// 开头) - 以便能够覆盖该副本,如果使用决定在一段时间后覆盖它。
推荐阅读
- c# - XmlDocument,预格式化的 xml:仅在 XML 声明后添加新行
- matlab - 如何使用 fft 找到周期信号的最大频率?
- python - 有没有更好的方法来标记一些字符串?
- c# - 如何更改通过 PrefabUtility.InstantiatePrefab 实例化的 GameObject 的父级?
- c# - 尝试选择单个节点会返回错误“表达式必须计算为节点集”。
- r - ifelse 语句从同一 df 行返回值
- python-3.x - 是否可以为无监督学习自定义 tf.estimator,自定义评估图没有损失?
- r - 在 R 中构建迭代 URL 时转义“%”
- c++ - std::map 给出类型转换错误,但仅在为 x86 编译时
- python - 使用 Pandas,我可以检测到固定列中的错误元素并返回该值吗?