Selecting a photo from the gallery, I want to capture its path on the device to use it as an avatar in my app

Grime 786 Reputation points
2021-09-02T10:18:29.263+00:00

I am using Xamarin.Essentials Media Picker to select a photo from the Gallery to be used in my app as an avatar. I want to store that photo path in a SQLite database so I can draw on it anytime later. At the moment I am getting paths that look very "temporary". I want to know how to get a permanent path to the photo. These are the paths I am getting from the selected image.

Android: 128671-screenshot-20210902-192857.jpg
iOS: 128721-img-8607.png

The C# code-behind looks like this:

using HandsFreeNotes.Data;  
using HandsFreeNotes.Model;  
using HandsFreeNotes.ViewModel;  
using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using Xamarin.Essentials;  
using Xamarin.Forms;  
using Xamarin.Forms.Xaml;  
  
namespace HandsFreeNotes.View  
{  
    [XamlCompilation(XamlCompilationOptions.Compile)]  
    public partial class NewOperatorPage : ContentPage  
    {  
        public NewOperatorPage()  
        {  
            // add a bit of padding to cater to the "notch" on the iPhone.  
            if (Device.RuntimePlatform == Device.iOS)  
            {  
                Padding = new Thickness(0, 40, 0, 0);  
            }  
  
            InitializeComponent();  
        }  
  
        private async void BackButton_Clicked(object sender, EventArgs e)  
        {  
            await Navigation.PopModalAsync();  
        }  
  
        private async void OKButton_Clicked(object sender, EventArgs e)  
        {  
            //var name = NameEntry.Text;  
            //var Phone = PhoneEntry.Text;  
            //var Email = EmailEntry.Text;  
            //var Avatar = AvatarEntry.Text;  
  
            //OperatorViewModel.OperatorList.Add(new OperatorModel(OperatorViewModel.OperatorList.Count, name, Phone, Email, Avatar));  
  
            var todoItem = (OperatorModel)BindingContext;  
            HFNDatabase database = await HFNDatabase.Instance;  
            await database.SaveItemAsync(todoItem);  
  
            await Navigation.PopModalAsync();  
        }  
  
        private async void CancelButton_Clicked(object sender, EventArgs e)  
        {  
            await Navigation.PopModalAsync();  
        }  
  
        async void AvatarEntry_Clicked(object sender, EventArgs e)  
        {  
            var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions  
            {  
                Title = "Please pick a photo to use as an Avatar..."  
            });  
  
            if (result != null)  
            {  
                var stream = await result.OpenReadAsync();  
  
                resultImage.Source = ImageSource.FromStream(() => stream);  
  
                // string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);  
                string localFilename = result.FileName;  
                string localPath = result.FullPath;  
                // string actualPath = result.OpenReadAsync();  
                // string newFilename = "hfn.jpeg";  
                // string localPath = Path.Combine(documentsPath, localFilename);  
                // string newPath = Path.Combine(documentsPath, newFilename);  
                // File.WriteAllBytes(newPath, result);  
                // var newStream = File.OpenWrite(newPath);  
                // await stream.CopyToAsync(newStream);  
  
  
  
                await DisplayAlert("Alert", localPath, "OK");  
  
            }  
        }  
    }  
}  
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,315 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 70,966 Reputation points Microsoft Vendor
    2021-09-03T06:11:41.91+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    If you do not want to store the image to Cache folder in your application path.

    You can copy your select image to File folder in your application path like following screenshot.

    128898-image.png

    Here is code. I use FileSystem.AppDataDirectory path to copy it

       private async void Button_Clicked(object sender, EventArgs e)  
               {  
                  
                  await TakePhotoAsync();  
               }  
         
               string PhotoPath;  
               async Task TakePhotoAsync()  
               {  
                   try  
                   {  
                       var photo = await MediaPicker.PickPhotoAsync();  
                       await LoadPhotoAsync(photo);  
                       Console.WriteLine($"CapturePhotoAsync COMPLETED: {PhotoPath}");  
         
                        DisplayAlert("in", PhotoPath, "OK");  
                   }  
                   catch (FeatureNotSupportedException fnsEx)  
                   {  
                       // Feature is not supported on the device  
                   }  
                   catch (PermissionException pEx)  
                   {  
                       // Permissions not granted  
                   }  
                   catch (Exception ex)  
                   {  
                       Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");  
                   }  
               }  
         
               async Task LoadPhotoAsync(FileResult photo)  
               {  
                   // canceled  
                   if (photo == null)  
                   {  
                       PhotoPath = null;  
                       return;  
                   }  
                   // save the file into local storage  
                   var newFile = Path.Combine(FileSystem.AppDataDirectory, photo.FileName);  
         
                 
                   using (var stream = await photo.OpenReadAsync())  
                   using (var newStream = File.OpenWrite(newFile))  
                       await stream.CopyToAsync(newStream);  
         
                   PhotoPath = newFile;  
               }  
    

    Best Regards,

    Leon Lu


    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 additional answers

Sort by: Most helpful