立即将图像加载到内存中

Vác*_*ych 2 memory wpf rendering tiff frames

我需要打开WPF中的Tiff图像到内存中的所有帧,然后删除源.之后,我最终需要渲染该图像(根据窗口大小调整大小).我的解决方案非常慢,我无法在第一次要求之前删除文件源.任何最佳做法?

Ray*_*rns 7

使用 CacheOption = BitmapCacheOption.OnLoad

此选项可以与BitmapImage.CacheOption属性一起使用,也可以作为参数使用.BitmapDecoder.Create() 如果要在加载图像后访问多个帧,则必须使用BitmapDecoder.Create.在任何一种情况下,文件都将完全加载并关闭.

另见我对这个问题的回答

更新

以下代码适用于加载图像的所有帧并删除文件:

var decoder = BitmapDecoder.Create(new Uri(imageFileName), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
List<BitmapFrame> images = decoder.Frames.ToList();
File.Delete(imageFileName);
Run Code Online (Sandbox Code Playgroud)

当然,您也可以在删除文件后访问decoder.Frames.

如果您希望自己打开流,此变体也可以使用:

List<BitmapFrame> images;
using(var stream = File.OpenRead(imageFileName))
{
  var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
  images = decoder.Frames.ToList();
}
File.Delete(imageFileName);
Run Code Online (Sandbox Code Playgroud)

在任何一种情况下,它都比创建a更有效,MemoryStream因为a MemoryStream一次在内存中保存两个数据副本:解码后的副本和未解码的副本.