8

I'm trying to do a super simple thing : get the size of an image.

So I create my BitmapImage but I'm getting 0 when I try to access the PixelWidth and PixelHeight.

How can I accomplish that please?

EDIT: (added sample code)

I'm just doing:

var baseUri = new Uri("ms-appx:///");
var bitmapImage = new BitmapImage(new Uri(baseUri, "Assets/Logo.png"));

MyImage.Source = bitmapImage;

Debug.WriteLine("Width: " + bitmapImage.PixelWidth + " Height: " + bitmapImage.PixelHeight);

In the console, I get:

Width: 0 Height: 0
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
Antoine Gamond
  • 802
  • 1
  • 10
  • 19
  • Most likely, the image was not loaded correctly. Set a breakpoint in the debugger and examine the contents of `image`. Alternative, try and display the contents of `image` somewhere on a window. Can you see anything? Is there even an image there? – Cody Gray - on strike Mar 14 '13 at 10:19
  • @CodyGray. Yes the image is perfectly displayed. – Antoine Gamond Mar 14 '13 at 10:20

2 Answers2

5

When you want to use the image properties after setting the source for your BitmapImage, you normally have to write an event handler that will execute on ImageOpened.

Also remember that ImageOpened only fires if the image is downloaded and decoded (i.e. using Image.Source).

var bitmapImage = new BitmapImage(uri);
bitmapImage.ImageOpened += (sender, e) => 
{
    Debug.WriteLine("Width: {0}, Height: {1}",
        bitmapImage.PixelWidth, bitmapImage.PixelHeight);
};
image.Source = bitmapImage;
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
  • 4
    Is there a way to force the image to be downloaded (without setting image.source)? – Cam Jul 17 '13 at 03:38
-2

You can try to initialyze it in a different way. Try this:

BitmapImage myBitmapImage = new BitmapImage();

// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(@"C:\pics\Water_Lilies.jpg");
myBitmapImage.EndInit();
int w = myBitmapImage.PixelWidth;
user2160696
  • 699
  • 3
  • 8
  • 21