2010-09-29 140 views
3

我工作的WPF應用程序有多個畫布和大量的按鈕。用戶可以加載圖像來更改按鈕背景。WPF BitmapImage內存問題

這是我在對象的BitmapImage

bmp = new BitmapImage(); 
bmp.BeginInit(); 
bmp.CreateOptions = BitmapCreateOptions.IgnoreImageCache; 
bmp.CacheOption = BitmapCacheOption.OnLoad; 
bmp.UriSource = new Uri(relativeUri, UriKind.Relative); 
bmp.EndInit(); 

和EndInit()的應用程序的存儲器的生長速度非常大的負荷的圖像的代碼。

一兩件事,使得想更好的(但並沒有真正解決問題)是增加

bmp.DecodePixelWidth = 1024; 

1024 - 我的最大畫布大小。但我應該只對寬度大於1024的圖像執行此操作 - 那麼如何在EndInit()之前獲取寬度?

回答

5

通過將圖像加載到BitmapFrame我想你只需閱讀元數據即可。

private Size GetImageSize(Uri image) 
{ 
    var frame = BitmapFrame.Create(image); 
    // You could also look at the .Width and .Height of the frame which 
    // is in 1/96th's of an inch instead of pixels 
    return new Size(frame.PixelWidth, frame.PixelHeight); 
} 

然後你就可以在加載的BitmapSource時,請執行下列操作:

var img = new Uri(ImagePath); 
var size = GetImageSize(img); 
var source = new BitmapImage(); 
source.BeginInit(); 
if (size.Width > 1024) 
    source.DecodePixelWidth = 1024; 
source.CreateOptions = BitmapCreateOptions.IgnoreImageCache; 
source.CacheOption = BitmapCacheOption.OnLoad; 
source.UriSource = new Uri(ImagePath); 
source.EndInit(); 
myImageControl.Source = source; 

我這個測試了幾次,看着在任務管理器中的內存消耗和差異巨大的(上10MP照片,我通過加載@ 1024而不是4272像素寬度來保存幾乎40MB的私人內存)

+0

哇,它真的給我留下了深刻的印象 - 這不僅在內存使用方面,而且在性能方面也是如此。感謝您提供一個非常簡單明瞭的答案 - 對於照片庫文件瀏覽器來說,這僅僅解決了我遇到的一些問題! – tpartee 2016-06-24 00:53:43