【发布时间】:2013-02-15 17:02:53
【问题描述】:
我有一个 BitmapImage,我想获取 PixelHeight 和 PixelWidth 属性,以便确定它是横向布局还是纵向布局。在确定其布局后,我需要设置图像的高度或宽度,以使其适合我的图像查看器窗口,而不会扭曲高度:宽度比。但是,看来我必须调用 BeginInit() 才能对我的图像做任何事情。我必须调用 EndInit() 来获取 PixelHeight 或 PixelWidth 属性,并且我不能在同一个 BitmapImage 对象上多次调用 BeginInit()。那么如何设置图像、获取高度和宽度、确定其方向然后调整图像大小?
这是我一直在使用的代码块:
image.BeginInit();
Uri imagePath = new Uri(path + "\\" + die.Die.ImageID + "_" + blueTape + "_BF.BMP");
image.UriSource = imagePath;
//image.EndInit();
imageHeight = image.PixelHeight;
imageWidth = image.PixelWidth;
//image.BeginInit();
// If the image is taller than it is wide, limit the height of the image
// i.e. DML87s and all non-rotated AOI devices
if (imageHeight > imageWidth)
{
image.DecodePixelHeight = 357;
}
else
{
image.DecodePixelWidth = 475;
}
image.EndInit();
当我运行它时,我得到了这个运行时异常:
无效操作异常:
BitmapImage 初始化未完成。调用 EndInit 方法 完成初始化。
有人知道如何处理这个问题吗?
【问题讨论】:
-
为什么需要设置
DecodePixelWidth或DecodePixelHeight?不能简单的把图片放到一个大小合适的Image控件中吗? -
看起来更容易以原始尺寸加载图像,然后稍后使用 ScaleTransform 来实现所需的效果。
-
@Clemens:如果我不设置 DecodePixel(Height/Width) 属性(y/ies),我的图像将是正常大小,无法正确放入面板。我的图像将是 1216x1616 或 1616x1216,具体取决于图像。我需要任何边的最大长度不超过 475 像素。
-
Image 控件将根据其Stretch 属性自动缩放位图。
标签: c# .net wpf graphics imaging