Setting BitmapImage as ImageSource in UWP not working

六月ゝ 毕业季﹏ 提交于 2019-12-11 17:46:54

问题


I am trying set the source of an Image in code with a BitmapImage but nothing shows up here is my code:

xaml:

<Image x:Name="img" HorizontalAlignment="Center"  VerticalAlignment="Center" Stretch="Fill" />

Code behind:

var image =  new BitmapImage(new Uri(@"C:\Users\XXX\Pictures\image.jpg", UriKind.Absolute));
image.DecodePixelWidth = 100;
this.img.Source = image;

回答1:


It's a permissions issue. Your app doesn't have direct access to read c:\users\XXX and so it fails to load the BitmapImage from that path. See Files and folders in the Music, Pictures, and Videos libraries

Assuming that c:\Users\XXX\Pictures is the current users Pictures library and that the app has the Pictures Library capability then you can get a brokered handle to the image file and load it with BitmapImage.SetSourceAsync.

I assume that your code here is simplified for demonstration, as the Pictures library is a user-centric location outside of the app's control. The app can't generally assume that a hard coded image name will be there.

        // . . .
        await SetImageAsync("image.jpg");
        // . . . 
    }

    private async Task SetImageAsync(string imageName)
    {
        // Load the imageName file from the PicturesLibrary
        // This requires the app have the picturesLibrary capability
        var imageFile = await KnownFolders.PicturesLibrary.GetFileAsync(imageName);
        using (var imageStream = await imageFile.OpenReadAsync())
        {
            var image = new BitmapImage();
            image.DecodePixelWidth = 100;

            // Load the image from the file stream
            await image.SetSourceAsync(imageStream);
            this.img.Source = image;
        }
    }


来源:https://stackoverflow.com/questions/51621758/setting-bitmapimage-as-imagesource-in-uwp-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!