WPF图像缓存

Mik*_*ter 8 wpf image

我有一个WPF应用程序从视频文件中获取快照图像.用户可以定义从中获取图像的时间戳.然后将图像保存到磁盘上的临时位置,然后将其渲染为<image>元素.

然后,用户应该能够选择不同的时间戳,然后覆盖磁盘上的临时文件 - 然后应该在<image>元素中显示.

使用Image.Source = null;,我可以从元素中清除图像文件<image>,因此它会显示一个空白区域.但是,如果源图像文件随后被新图像(具有相同名称)覆盖并加载到<image>元素中,则它仍然显示旧图像.

我使用以下逻辑:

// Overwrite temporary file file here

// Clear out the reference to the temporary image
Image_Preview.Source = null;

// Load in new image (same source file name)
Image = new BitmapImage();
Image.BeginInit();
Image.CacheOption = BitmapCacheOption.OnLoad;
Image.UriSource = new Uri(file);
Image.EndInit();
Image_Preview.Source = Image;
Run Code Online (Sandbox Code Playgroud)

<image>即使原始文件已完全替换,元素中显示的图像也不会更改.这里是否存在我不知道的图像缓存问题?

Cle*_*ens 15

默认情况下,WPF会缓存从URI加载的BitmapImages.

你可以通过设置BitmapCreateOptions.IgnoreImageCache标志来避免这种情况:

var image = new BitmapImage();

image.BeginInit();
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(file);
image.EndInit();

Image_Preview.Source = image;
Run Code Online (Sandbox Code Playgroud)

或者直接从Stream加载BitmapImage:

var image = new BitmapImage();

using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.StreamSource = stream;
    image.EndInit();
}

Image_Preview.Source = image;
Run Code Online (Sandbox Code Playgroud)