【问题标题】:Can't load image with path from FromFile in UWP无法在 UWP 中使用 FromFile 中的路径加载图像
【发布时间】:2019-10-13 05:22:39
【问题描述】:

我正在开发适用于 Android 和 UWP 的应用。在一个屏幕中,我需要从设备文件系统加载图像并显示它。奇怪的是,它在 Android 上完美运行,但在 UWP 上却不行。 FilePicker 似乎正确返回了路径...

我的 XAML

<Image Grid.Row="0" Grid.Column="0" 
Source="{Binding NewImage}" Margin="10,10,10,10" Aspect="AspectFit" 
VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />

图片来源

private FileImageSource _newImage;
public FileImageSource NewImage
        {
            get { return _newImage; }
            set
            {
                _newImage = value;
                OnPropertyChanged(nameof(NewImage));
            }
        }

应该加载图像并设置路径的函数。

private async void OnAddImage()
        {
            string[] types = { ".jpg", ".png" };
            FileData temp = await CrossFilePicker.Current.PickFile(types);
            if (temp == null)
            {
                return;
            }
            Debug.WriteLine($"ImagePath: {temp.FilePath}");
            Debug.WriteLine($"ImageName: {temp.FileName}");
            NewEntry.ImagePath = temp.FilePath;
            NewImage = (FileImageSource)ImageSource.FromFile(temp.FilePath);
        }

【问题讨论】:

    标签: c# xamarin.forms uwp imagesource fromfile


    【解决方案1】:

    当您使用文件选择器在 UWP 上选择图像时,这些图像可能会存储在外部磁盘上。我们只能使用一个路径来加载项目中嵌入的文件或者UWP本地存储中存储的文件:https://blogs.msdn.microsoft.com/wsdevsol/2012/12/04/skip-the-path-stick-to-the-storagefile/

    所以调整你的加载事件:

    string[] types = { ".jpg", ".png" };
    FileData temp = await CrossFilePicker.Current.PickFile(types);
    if (temp == null)
    {
        return;
    }
    Debug.WriteLine($"ImagePath: {temp.FilePath}");
    Debug.WriteLine($"ImageName: {temp.FileName}");
    //NewEntry.ImagePath = temp.FilePath;
    NewImage = (StreamImageSource)ImageSource.FromStream(() => temp.GetStream());
    
    // Property
    private StreamImageSource _newImage;
    public StreamImageSource NewImage
    {
        get { return _newImage; }
        set
        {
            _newImage = value;
            OnPropertyChanged(nameof(NewImage));
        }
    }
    

    这也适用于 Android。

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多