[FIXED] How to get Image from directory path in xamarin forms

Issue

I want to retrieve image which i have it’s path in phone

filepath = "/storage/emulated/0/Android/data/com.CommunicatorEye/files/Pictures/EmployeesCards/IMG_20190131_143513.jpg";

var image = DependencyService.Get<IDependency().RetriveImageFromLocation(filepath);

IDependency.cs

 public interface IDependency
    {
        Task<Image> RetriveImageFromLocation(string location);
    }

Android
DependencyImplementation.cs

public async Task<Image> RetriveImageFromLocation(string location)
        {
            Image image = new Image();
            var memoryStream = new MemoryStream();

            using (var source = System.IO.File.OpenRead(location))
            {
                await source.CopyToAsync(memoryStream);
            }

            image.Source = ImageSource.FromStream(() => memoryStream);
            return image;
        }

but it doesn’t work for me , any sample ?

Solution

If that file is within your app’s sandbox, there is no reason to use DI/DependencyService/etc… to obtain a stream to populate an ImageSource and then add that to an Image.

Use an FileImageSource (static ImageSource.FromFile) and supply it the path:

var image = new Image
{
    Source = ImageSource.FromFile(filePath)
};

Answered By – SushiHangover

Answer Checked By – David Goodson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published