1

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;
Federico Navarrete
  • 3,069
  • 5
  • 41
  • 76
Joe B
  • 738
  • 7
  • 28
  • Do you have a viewModel maybe? then you can just set the source property to a binding?Also maybe to can look at [https://stackoverflow.com/questions/1491383/reloading-an-image-in-wpf](https://stackoverflow.com/questions/1491383/reloading-an-image-in-wpf) – mahlatse Jul 31 '18 at 20:43
  • that link is for WPF – Joe B Jul 31 '18 at 20:51
  • Could it not be the same issue you are having with your image source not updating?I haven't gotten into UWP yet and had hoped it would use the same logic as WPF for something like this. – mahlatse Jul 31 '18 at 20:54

1 Answers1

2

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;
        }
    }
Rob Caplan - MSFT
  • 21,714
  • 3
  • 32
  • 54