8

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?

1 Answer 1

22

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.