3

我在一个有多个画布和很多按钮的 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() 之前的宽度?

4

1 回答 1

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 的私有内存)

于 2010-09-29T08:33:08.450 回答