BitmapImage returns 0 for PixelWidth and PixelHeight

I am trying to do a very simple thing: get the image size.

So, I create my BitmapImage , but get 0 when I try to access PixelWidth and PixelHeight .

How can I do this please?

EDIT: (added sample code)

I just do:

 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 
+4
source share
2 answers

If you want to use image properties after setting the source for BitmapImage , you usually need to write an event handler that will execute ImageOpened .

Also remember that ImageOpened only starts when loading and decoding an image (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; 
+3
source

You can try to initialize it differently. Try the following:

 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; 
-1
source

Source: https://habr.com/ru/post/1469192/


All Articles