首页 文章

WPF图像缓存

提问于
浏览
8

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

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

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

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

1 回答

  • 13

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

    或者直接从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;
    

相关问题