Hello,
there's more. I also need to write the image to where the app has access to it as well as to the Gallery (developing on Android for now but will use the app on iOS as well).
For this thread, lets focus on the android platform. For iOS issue, please open a new thread in this site.
As note:Avoid posting multiple questions in a single thread
Firstly, you cannot get Stream by using Stream stream = await ((StreamImageSource)myImage.Source). Stream(CancellationToken.None);
, this line does not guarantee that the images are in an app-readable format or imagesource type.
we can get stream by Stream stream = await cameraView.TakePhotoAsync();
directly and you can use ContentResolver
to save this image to the gallery like following code.
private async void Button_Clicked(object sender, EventArgs e)
{
Stream stream = await cameraView.TakePhotoAsync();
#if ANDROID
try
{
ContentResolver resolver = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.ContentResolver;
ContentValues contentValues = new ContentValues();
contentValues.Put(MediaStore.Images.ImageColumns.DisplayName, "test.png");
contentValues.Put(MediaStore.Images.ImageColumns.DateTaken, DateTime.UtcNow.ToUniversalTime().ToString());
contentValues.Put(MediaStore.Images.ImageColumns.DateAdded, DateTime.UtcNow.ToUniversalTime().ToString());
contentValues.Put(MediaStore.Images.ImageColumns.Size, stream.Length);
contentValues.Put(MediaStore.Images.ImageColumns.MimeType, "image/png");
contentValues.Put(MediaStore.Images.ImageColumns.RelativePath, Android.OS.Environment.DirectoryPictures);
Android.Net.Uri uri = resolver.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
Stream outputStream = resolver.OpenOutputStream(uri);
await stream.CopyToAsync(outputStream);
}
catch (Exception e1)
{
Console.WriteLine(e1.ToString());
throw;
}
#endif
}
By the way, please do not forget to add following used namespaces.
#if ANDROID
using Android.Content;
using Android.Provider;
#endif
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.