WPF BitmapImage Memory Problem
I work on a WPF application that has multiple canvases and lots of buttons. The user cand load images to change the button background.
This is the code where I load the image in the BitmapImage object
bmp = new BitmapImage();
bmp.BeginInit();
bmp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bmp.CacheOption = BitmapCacheO开发者_JAVA百科ption.OnLoad;
bmp.UriSource = new Uri(relativeUri, UriKind.Relative);
bmp.EndInit();
and on EndInit() application's memory grows very much.
One thing that makes thinks better (but doesn't really fix the problem) is adding
bmp.DecodePixelWidth = 1024;
1024 - my maximum canvas size. But I should do this only to the images with width greater than 1024 - so how can I get the width before EndInit() ?
By loading the image into a BitmapFrame I think you'll get by with just reading the metadata.
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);
}
And then you can do the following when loading the 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;
I tested this a few times and looked at the memory consumption in the Task Manager and the difference was massive (on a 10MP photo, I saved almost 40MB of private memory by loading it @ 1024 instead of 4272 pixels width)
精彩评论