Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting an Image that has been used by a WPF control

I would like to bind an Image to some kind of control an delete it later on.

path = @"c:\somePath\somePic.jpg"
FileInfo fi = new FileInfo(path);
Uri uri = new Uri(fi.FullName, UriKind.Absolute);
var img = new System.Windows.Controls.Image();
img.Source = new BitmapImage(uri);

Now after this code I would like to delete the file :

fi.Delete();

But I cannot do that since the image is being used now. Between code fragment 1 en 2 what can I do to release it?

like image 378
Peter Avatar asked Mar 11 '10 08:03

Peter


2 Answers

You could use a MemoryStream but that actually wastes memory because two separate copies of the bitmap data are kept in RAM: When you load the MemoryStream you make one copy, and when the bitmap is decoded another copy is made. Another problem with using MemoryStream in this way is that you bypass the cache.

The best way to do this is to read directly from the file using BitmapCacheOptions.OnLoad:

path = @"c:\somePath\somePic.jpg"

var source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
source.CacheOption = BitmapCacheOption.OnLoad;
source.EndInit();  // Required for full initialization to complete at this time

var img = new System.Windows.Controls.Image { Source = source };

This solution is efficient and simple too.

Note: If you actually do want to bypass the cache, for example because the image may be changing on disk, you should also set CreateOption = BitmapCreateOption.IgnoreImageCache. But even in that case this solution outperforms the MemoryStream solution because it doesn't keep two copies of the image data in RAM.

like image 77
Ray Burns Avatar answered Nov 13 '22 23:11

Ray Burns


copy the image to MemoryStream before giving to imagesource it should look like this

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = 30;
bi.StreamSource = byteStream;
bi.EndInit();

where byteStream is copy of file in MemoryStream

also this can be useful

like image 20
Arsen Mkrtchyan Avatar answered Nov 13 '22 22:11

Arsen Mkrtchyan