BitmapImage returns 0 for PixelWidth and PixelHeight

南楼画角 提交于 2019-12-23 08:12:04

问题


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

回答1:


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;



回答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;


来源:https://stackoverflow.com/questions/15406315/bitmapimage-returns-0-for-pixelwidth-and-pixelheight

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