Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Image Caching

Tags:

image

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.

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.

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.

I am using the following logic:

// 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?

like image 703
Mike Baxter Avatar asked May 11 '15 09:05

Mike Baxter


1 Answers

By default, WPF caches BitmapImages that are loaded from URIs.

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;

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;
like image 183
Clemens Avatar answered Oct 19 '22 02:10

Clemens