Search code examples
c#xamluwp

Setting BitmapImage as ImageSource in UWP not working


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;

Solution

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