如何从Xamarin形式的目录路径中获取图像

时间:2019-02-03 15:00:19

标签: xamarin xamarin.forms

我想检索手机中有路径的图像

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

但是对我来说不起作用,有没有样品?

1 个答案:

答案 0 :(得分:1)

如果该文件在您应用的沙箱中,则没有理由使用DI / DependencyService / etc ...获取流以填充ImageSource,然后将其添加到Image

使用FileImageSource(静态ImageSource.FromFile)并提供路径:

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