WPF 图像缓存 [英] WPF Image Caching
问题描述
我有一个 WPF 应用程序,可以从视频文件中获取快照图像.用户可以定义从中获取图像的时间戳.然后将图像保存到磁盘上的临时位置,然后渲染到
元素中.
I have a WPF application that takes a snapshot image from a video file. The user can define the timestamp from which to take the image. The image is then saved to a temporary location on disk, and is then rendered into an <image>
element.
然后用户应该能够选择不同的时间戳,然后覆盖磁盘上的临时文件 - 然后这应该显示在 <image>
元素中.
The user should then be able to select a different timestamp, which then overwrites the temporary file on disk - this should then be displayed within the <image>
element.
使用 Image.Source = null;
,我可以从
元素清除图像文件,所以它显示一个空格代替.但是,如果源图像文件随后被新图像(具有相同名称)覆盖并加载到
元素中,它仍然显示旧图像.
Using Image.Source = null;
, I can clear the image file from the <image>
element, so it displays a blank space instead. However, if the source image file is then overwritten with a new image (with the same name) and loaded into the <image>
element, it still shows the old 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;
显示在
元素中的图像不会改变,即使原始文件已被完全替换.此处是否存在我不知道的图像缓存问题?
The image displayed in the <image>
element does not change, even though the original file has been completely replaced. Is there an image caching issue here that I am not aware of?
推荐答案
默认情况下,WPF 缓存从 URI 加载的 BitmapImages.
By default, WPF caches BitmapImages that are loaded from URIs.
您可以通过设置 BitmapCreateOptions.IgnoreImageCache
标志来避免这种情况:
You can avoid that by setting the BitmapCreateOptions.IgnoreImageCache
flag:
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:
Or you load the BitmapImage directly from a Stream:
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;
这篇关于WPF 图像缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!