我上具有多个画布和许多按钮的WPF应用程序工作。用户CAND负载的图像来改变按钮的背景

这是我在对象的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照片,我通过加载它保存的私有存储器几乎40MB @ 1024,而不是4272个像素的宽度)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top