我想映像绑定到某种控制的删除它以后。

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 EN 2之间我能做些什么来释放它?

有帮助吗?

解决方案

给予ImageSource的前复制图像的MemoryStream 它应该是这样的

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

,其中的字节流是文件中的MemoryStream复制

可以是有用的

其他提示

您可以使用MemoryStream但由于位图数据的两个单独的副本被保存在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中。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top