WPF图像缓存

8
我有一个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;
< p >尽管完全替换了原始文件,但在< code ><image>元素中显示的图像没有更改。这里是否存在图像缓存问题,我不太清楚?< /p >
1个回答

22

默认情况下,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;

或者您可以直接从流中加载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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接