开发者

Deleting an Image that has been used by a WPF control

开发者 https://www.devze.com 2022-12-22 09:45 出处:网络
I would like to bind an Image to some kind of control an delete it later on. path = @\"c:\\somePath开发者_如何转开发\\somePic.jpg\"

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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号