【问题标题】:Getting BitmapImage PixelHeight Property causes Initialization Issues获取 BitmapImage PixelHeight 属性会导致初始化问题
【发布时间】: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 方法 完成初始化。

有人知道如何处理这个问题吗?

【问题讨论】:

  • 为什么需要设置DecodePixelWidthDecodePixelHeight?不能简单的把图片放到一个大小合适的Image控件中吗?
  • 看起来更容易以原始尺寸加载图像,然后稍后使用 ScaleTransform 来实现所需的效果。
  • @Clemens:如果我不设置 DecodePixel(Height/Width) 属性(y/ies),我的图像将是正常大小,无法正确放入面板。我的图像将是 1216x1616 或 1616x1216,具体取决于图像。我需要任何边的最大长度不超过 475 像素。
  • Image 控件将根据其Stretch 属性自动缩放位图。

标签: c# .net wpf graphics imaging


【解决方案1】:

据我所知,如果不对位图进行两次解码,您想要做的事情是不可能的。

我想将位图解码为其原始大小然后根据需要设置包含图像控件的大小会简单得多。位图进行了适当的缩放,因为Stretch 设置为Uniform(由于图像控件的宽度和高度都设置了,Stretch 也可以设置为FillUniformToFill)。

var bitmap = new BitmapImage(new Uri(...));

if (bitmap.Width > bitmap.Height)
{
    image.Width = 475;
    image.Height = image.Width * bitmap.Height / bitmap.Width;
}
else
{
    image.Height = 475;
    image.Width = image.Height * bitmap.Width / bitmap.Height;
}

image.Stretch = Stretch.Uniform;
image.Source = bitmap;

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    相关资源
    最近更新 更多