6

我想将图像绑定到某种控件,然后再将其删除。

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);

现在,在此代码之后,我想删除该文件:

fi.Delete();

但我不能这样做,因为现在正在使用该图像。在代码片段 1 和 2 之间我可以做些什么来释放它?

4

2 回答 2

14

您可以使用 aMemoryStream但实际上会浪费内存,因为位图数据的两个单独副本保存在 RAM 中:当您加载时,MemoryStream您制作一个副本,当位图被解码时,另一个副本被制作。以这种方式使用的另一个问题MemoryStream是您绕过缓存。

最好的方法是使用 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 };

该解决方案也高效且简单。

注意:如果您确实想绕过缓存,例如因为图像可能在磁盘上发生变化,您还应该设置CreateOption = BitmapCreateOption.IgnoreImageCache. 但即使在这种情况下,该解决方案也优于该MemoryStream解决方案,因为它不会在 RAM 中保留两个图像数据副本。

于 2010-03-11T10:27:23.507 回答
3

在提供给 imagesource 之前将图像复制到 MemoryStream 它应该看起来像这样

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

其中 byteStream 是 MemoryStream 中文件的副本

也很有用

于 2010-03-11T08:57:04.560 回答