首页 > 解决方案 > UWP为图像控件设置BitmapImage

问题描述

我正在使用 Prism 库来实现与 BitmapImage 的绑定图像。

这是 xml

<Button Grid.Row="1" Text="Resize Img" Command="{Binding ImageResize}"></Button>
<Image  Grid.Row="2" Source="{Binding ImageResult}"></Image>
<Image  Grid.Row="3" Source="{Binding ImageUri}"></Image>
<Label Text="{Binding ImageUri}"></Label>

这是 ImagePageViewModel

public class ImagePageViewModel : BindableBase
{
    public ImagePageViewModel()
    {

    }
    private string _imageUri;
    public string ImageUri
    {
        get { return _imageUri; }
        set { SetProperty(ref _imageUri, value); }
    }
    private BitmapImage _imageResult;
    public BitmapImage ImageResult
    {
        get { return _imageResult; }
        set { SetProperty(ref _imageResult, value); }
    }

    private DelegateCommand _imageSelect;
    public DelegateCommand ImageSelect =>
        _imageSelect ?? (_imageSelect = new DelegateCommand(ExecuteImageSelect));

    async void ExecuteImageSelect()
    {
        try
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker
            {
                ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
            };
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    // Set the image source to the selected bitmap 
                    BitmapImage bitmapImage = new BitmapImage();
                    //bitmapImage.DecodePixelWidth = 600; //match the target Image.Width, not shown
                    await bitmapImage.SetSourceAsync(fileStream);
                    ImageResult = bitmapImage;
                    ImageUri = file.Path;
                    //ImageUri = @"http://pic26.nipic.com/20121221/9252150_142515375000_2.jpg";
                }
            }
            else
            {
                ImageUri = "";
            }
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }        
}

对于上面的代码,设置ImageResult和设置 ImageUrifile.Path两者都不起作用。file.Path 返回文件的正确值。

它仅在与网络文件一起使用时有效。

如果您浏览本地磁盘文件,这与文件访问权限有关吗?

我认为这与 UWP 文件权限有关,但知道如何解决吗?

标签: data-bindinguwpbitmapbitmapimage

解决方案


该设置方式ImageResult适用于 UWP 平台。但是设置图像源file.Path不起作用。UWP 在沙盒中运行,我们无法使用 xaml 中的路径访问文件。我检查了你的代码,它看起来不像 uwp 项目。因为 UWP 不包含 Label 控件。如果项目是xamarin,请参考xamarin镜像文档

更新

Froms 项目是共享库,你不应该FileOpenPicker在其中调用 UWP。根据您的要求,您可以为 Xamarin 创建依赖服务并将位图转换为 Xamarin 图像源,更多请参考此案例


推荐阅读