首页 > 解决方案 > 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 ?

标签: androidxamarin.android

解决方案


经过我的验证,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:// 开头) - 以便能够覆盖该副本,如果使用决定在一段时间后覆盖它。


推荐阅读