2013-02-15 42 views
1

我有一個BitmapImage,我想獲得PixelHeight和PixelWidth屬性,因此我可以確定它是否具有橫向或縱向佈局。確定其佈局後,我需要設置圖像的高度或寬度,以使其適合我的圖像查看器窗口,而不會扭曲高度:寬度比。然而,看起來我必須調用BeginInit()才能對圖像執行任何操作。我必須調用EndInit()來獲取PixelHeight或PixelWidth屬性,並且我不能在同一個BitmapImage對象上多次調用BeginInit()。那麼,我該如何設置圖像,獲取高度和寬度,確定其方向,然後調整圖像大小?獲取BitmapImage PixelHeight屬性導致初始化問題

下面的代碼,我一直在與塊:

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

當我運行它,我得到這個運行時異常:

出現InvalidOperationException:

的BitmapImage初始化不完整。調用EndInit方法到 完成初始化。

有沒有人知道如何處理這個問題?

+0

爲什麼你需要設置'DecodePixelWidth'或'DecodePixelHeight'呢?你不能簡單地把圖像放入一個適當大小的'Image'控件嗎? – Clemens 2013-02-15 17:09:15

+0

似乎只是將圖像加載到其原始尺寸會更容易,然後稍後使用ScaleTransform來達到所需的效果。 – 2013-02-15 17:10:03

+0

@Clemens:如果我沒有設置DecodePixel(高度/寬度)屬性(y/iies),我的圖像將是其正常尺寸,並且不能正確放入面板。根據圖像,我的圖像將爲1216x1616或1616x1216。我需要任何一方的最大長度不超過475像素。 – kformeck 2013-02-15 17:16:32

回答

2

就我所知,如果不解碼位圖兩次,你想要做的事是不可能的。

我想只要將位圖解碼爲原始大小,然後根據需要設置包含Image控件的大小就簡單多了。因爲Stretch設置爲Uniform(因爲Image控件的寬度和高度均已設置,所以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;