简体   繁体   English

如何获得图像的宽度和高度

[英]How to get the width and height of an image

I am trying to get the height of an image like the following 我试图获得如下图像的高度

BitmapImage bitmap = new BitmapImage(new Uri("Images/header.png",UriKind.RelativeOrAbsolute));
Debug.WriteLine("bitmap.PixelHeight : " + bitmap.PixelHeight); 

It is printing the height as 0, but the actual image's height is 35 pixels. 它将高度打印为0,但实际图像的高度为35像素。 It is not an image loaded from server. 它不是从服务器加载的图像。 It is stored inside the application bundle itself. 它存储在应用程序包本身中。

If though it's not loaded from a server, it may still be loaded and processed asynchronously. 如果它没有从服务器加载,它仍然可以异步加载和处理。 If you use the same Debug.WriteLine call after you know the image is visible, does that give the right results? 如果您在知道图像可见后使用相同的Debug.WriteLine调用,那么它是否会产生正确的结果?

Do you use your bitmap later in your project? 你以后在项目中使用你的位图吗? If you are using it as Source in Image, you can try Image.ActualHeight and Image.ActualWidth 如果您在图像中将其用作源,则可以尝试Image.ActualHeight和Image.ActualWidth

You have to wait for the ImageOpened event before you can get the Width/Heigth values. 您必须等待ImageOpened事件才能获得Width / Heigth值。 This is because the BitmapImage is being created asynchronously when loaded from a URI (even when the file is local). 这是因为从URI加载时异步创建BitmapImage(即使文件是本地的)。 Only if you load it from a stream it gets created synchronously. 只有从流中加载它才会同步创建。

The other thing to be aware of is that BitmapImage.CreateOption is by default set to DelayCreation, which means it will only be created when the BitmapImage is assigned to an element in the live tree. 另一件需要注意的是BitmapImage.CreateOption默认设置为DelayCreation,这意味着只有在将BitmapImage分配给实时树中的元素时才会创建它。 You can set CreateOption = None to change that. 您可以设置CreateOption = None来更改它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM