I want to write a new image, either selected or newly captured, to the gallery

Grime 786 Reputation points
2021-08-26T07:27:37.06+00:00

I have quickly cobbled together an app that uses Xamarin.Essentials Media Picker. This successfully allows me to either pick or take a photo on both my iPhone 11 and my Samsung Galaxy S20 FE.
I don't know how to then store it to the media gallery so I can later pick it to work on it.

The code-behind is here:

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using Xamarin.Forms;  
using Xamarin.Essentials;  
using System.IO;  
  
namespace Avatar  
{  
    public partial class MainPage : ContentPage  
    {  
        public MainPage()  
        {  
            // add a bit of Thickness to cater to the "notch" on the iPhone.  
            if (Device.RuntimePlatform == Device.iOS) { Padding = new Thickness(0, 40, 0, 0); }  
  
            InitializeComponent();  
        }  
  
        async void SelectPhotoButton_Clicked(System.Object sender, EventArgs e)  
        {  
            var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions  
            {  
                Title = "Please pick a photo"  
            });  
  
            var stream = await result.OpenReadAsync();  
  
            resultImage.Source = ImageSource.FromStream(() => stream);  
        }  
  
        async void TakePhotoButton_Clicked(object sender, EventArgs e)  
        {  
            var result = await MediaPicker.CapturePhotoAsync();  
  
            if (result != null)  
            {  
                var stream = await result.OpenReadAsync();  
                resultImage.Source = ImageSource.FromStream(() => stream);  
  
                string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);  
                string localFilename = "downloaded.jpg";  
                string localPath = Path.Combine(documentsPath, localFilename);  
  
                await DisplayAlert("Alert", localPath, "OK");  
            }  
        }  
    }  
}  
![126653-image.png][1]![126526-image.png][2]  

The two images are paths and potential filenames for the required image.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,301 questions
0 comments No comments
{count} votes

Accepted answer
  1. JarvanZhang 23,951 Reputation points
    2021-08-27T06:21:56.93+00:00

    Hello @Grime ,

    Welcome to our Microsoft Q&A platform!

    I don't know how to then store it to the media gallery so I can later pick it to work on it.

    Do you mean saving the newly captured photos? The selected photos have been stored in the device, you could already pick them now. For this function, try using MediaPlugin instead. It provides the SaveToAlbum option when taking the new photo.

       var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions  
       {  
           SaveToAlbum = true  
       });  
    

    You can also achieve the function on each native platform. And then call the function code in the shared project using DependencyService.

       private async void Button_Clicked(object sender, EventArgs e)  
       {  
           var photo = await MediaPicker.CapturePhotoAsync();  
           var stream = await photo.OpenReadAsync();  
         
           MemoryStream ms = new MemoryStream();  
           stream.CopyTo(ms);  
           var bytes = ms.ToArray();  
         
           DependencyService.Get<ITestInterface>().StorePhotoToGallery(bytes, "test.png");  
       }  
         
       //platform implementation  
       [assembly: Xamarin.Forms.Dependency(typeof(TestImplementation))]  
       namespace TestApplication_5.Droid  
       {  
           public class TestImplementation : ITestInterface  
           {  
               public async void storePhotoToGallery(byte[] bytes, string fileName)  
               {  
                   Context context = MainActivity.Instance;  
                   try  
                   {  
                       Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);  
                       string path = System.IO.Path.Combine(storagePath.ToString(), fileName);  
                       System.IO.File.WriteAllBytes(path, bytes);  
                       var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);  
                       mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));  
                       context.SendBroadcast(mediaScanIntent);  
                   }  
                   catch (Exception ex)  
                   {  
                   }  
               }  
           }  
       }  
    

    For the iOS implementation, you could refer to: https://stackoverflow.com/a/60630182/11083277

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful