【问题标题】:WPF Image CachingWPF 图像缓存
【发布时间】:2015-05-11 09:29:52
【问题描述】:

我有一个从视频文件中获取快照图像的 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;

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

【问题讨论】:

    标签: wpf image


    【解决方案1】:

    默认情况下,WPF 缓存从 URI 加载的位图图像。

    您可以通过设置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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 2011-12-26
      • 2013-10-24
      • 2014-03-17
      • 2010-12-29
      • 2016-10-23
      相关资源
      最近更新 更多