Hello,
In MAUI, you can follow the steps below to save photo files to an album.
For iOS:
Step 1. Add the following permisson into plist.
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Please allow access to save photo in your photo library</string>
Step 2. Create SavePictureService.cs
in Platforms/iOS folder, and add the following code:
public static class SavePictureService
{
public static void SavePicture(byte[] arr)
{
var imageData = NSData.FromArray(arr);
var image = UIImage.LoadFromData(imageData);
image.SaveToPhotosAlbum((img, error) =>
{
});
}
}
For Android:
Step 1. Add the following code into MainActivity.cs
:
public static MainActivity Instance { get; private set; }
// Then, make the assignment in the OnCreate method.
Instance = this;
Step 2. Create SavePictureService.cs
in Platforms/Android
folder, and add the following code:
public static class SavePictureService
{
public static bool SavePicture(byte[] arr, string imageName)
{
var contentValues = new ContentValues();
contentValues.Put(MediaStore.IMediaColumns.DisplayName, imageName);
contentValues.Put(MediaStore.Files.IFileColumns.MimeType, "image/png");
contentValues.Put(MediaStore.IMediaColumns.RelativePath, "Pictures/relativePath");
try
{
var uri = MainActivity.Instance.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
var output = MainActivity.Instance.ContentResolver.OpenOutputStream(uri);
output.Write(arr, 0, arr.Length);
output.Flush();
output.Close();
}
catch (System.Exception ex)
{
Console.Write(ex.ToString());
return false;
}
contentValues.Put(MediaStore.IMediaColumns.IsPending, 1);
return true;
}
}
For MAUI, you could invoke those services in TakePhoto
method to save photo into album.
using Stream sourceStream = await photo.OpenReadAsync();
using FileStream localFileStream = File.OpenWrite(localFilePath);
// convert stream to byte[]
MemoryStream ms = new MemoryStream();
sourceStream.CopyTo(ms);
var b = ms.ToArray();
await sourceStream.CopyToAsync(localFileStream);
// save photo into album.
#if ANDROID
MauiApp22.Platforms.Android.SavePictureService.SavePicture(b, photo.FileName);
#elif IOS
MauiApp22.Platforms.iOS.SavePictureService.SavePicture(b);
#endif
Best Regards,
Alec Liu.
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.