Pregunta

I have a BitmapImage that I want to get the PixelHeight and PixelWidth properties so I can determine whether it has a landscape or portrait layout. After I determine its layout, I need to set either the height or width of the image to get it to fit into my image viewer window without distorting the height:width ratio. However, it appears I have to call BeginInit() in order to do anything with my image. I have to call EndInit() to get the PixelHeight or PixelWidth properties and I cannot call BeginInit() more than once on the same BitmapImage object. So how can I possibly set my image, get the height and width, determine its orientation and then resize the image?

Here the chunk of code that I have been working with:

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();

When I run this, I get this run-time exception:

InvalidOperationException:

BitmapImage initialization is not complete. Call the EndInit method to complete the initialization.

Does anybody know how to deal with this issue?

¿Fue útil?

Solución

As far as I know, what you want to do is not possible without decoding the bitmap twice.

I guess it would be a lot simpler to just decode the bitmap to its native size and then set the size of the containing Image control as needed. The bitmap is scaled appropriately, as Stretch is set to Uniform (since both width and height of the Image control are set, Stretch could as well be set to Fill or UniformToFill).

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;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top