Crop WPF Images

I have a WPF application that takes a snapshot from a video file. The user can determine the time stamp with which to make the image. The image is then saved to a temporary place on disk and then displayed in the <image> element.

Then the user can select another timestamp, which then overwrites the temporary file on disk - this should be displayed in the <image> element.

Using Image.Source = null; , I can clear the image file from the <image> element, so empty space is displayed instead. However, if the original image file is then overwritten with a new image (with the same name) and loaded into the <image> element, it still displays the old image .

I use 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 if the original file is completely replaced. Is there an image caching issue that I don't know about?

+6
source share
1 answer

By default, WPF caches BitmapImages that are loaded from the URI.

You can avoid this 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 BitmapImage directly from the 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; 
+10
source

Source: https://habr.com/ru/post/986959/


All Articles