question

Grime avatar image
0 Votes"
Grime asked Grime commented

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

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");
    
             }
         }
     }
 }



dotnet-xamarinforms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered Grime commented

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.



image.png (20.7 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@Grime May I know if you have got any chance to check my answer? I am glad to help if you have any other questions

0 Votes 0 ·

Sorry. I was away. Your answer works for Android.

0 Votes 0 ·