WPF最有效的图像加载方式

时间:2012-12-11 10:25:30

标签: wpf image performance

可能这听起来很愚蠢,但哪一个是加载图片最有效的方式?

A

BitmapImage bmp = new BitmapImage();
using(FileStream fileStream = new FileStream(source_path, FileMode.Open))
{
   bmp.BeginInit();
   bmp.CacheOption = BitmapCacheOption.OnLoad;
   bmp.StreamSource = fileStream;
   bmp.EndInit();
   if (bmp.CanFreeze)
      bmp.Freeze();

   images.source = bmp;
}

BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bmp.UriSource = new Uri(source_path);
bmp.EndInit();
if (bmp.CanFreeze)
   bmp.Freeze();

images.Source = bmp;

我记得我在某处读过从流中加载完全禁用缓存。如果这是真的,这是否意味着从流中加载在内存管理方面更好?

1 个答案:

答案 0 :(得分:1)

据我所知,当您通过设置其UriSource属性加载BitmapImage时,图像始终被缓存。我不知道有什么方法可以避免这种情况。至少设置BitmapCreateOptions.IgnoreImageCache仅确保不从缓存中检索图像,但它不会阻止图像存储在缓存中。

BitmapCreateOptions中的“备注”说明了

  

选择IgnoreImageCache时,图像中的所有现有条目   即使缓存共享相同的Uri

,也会替换缓存

我的结论是,当Uri加载图像时,缓存仅执行。换句话说,如果您确实需要禁止图像缓存,则必须通过其StreamSource属性加载图像。

然而,如果这真的“在内存管理方面更好”,或许值得一试。你可以尝试两种选择,看看你是否观察到内存消耗的任何显着差异。

相关问题