簡體   English   中英

WPF BitmapImage內存問題

[英]WPF BitmapImage Memory Problem

我在一個WPF應用程序上工作,該應用程序有多個畫布和許多按鈕。 用戶可以加載圖像以更改按鈕背景。

這是我在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()之前的寬度?

通過將圖像加載到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的私有內存)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM