删除 WPF 控件已使用的图像
我想将图像绑定到某种控件并稍后将其删除。
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之间我该怎么做才能释放它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
MemoryStream
但这实际上会浪费内存,因为位图数据的两个单独副本保存在 RAM 中:当您加载MemoryStream
时,您会制作一份副本,当位图被解码,另一个副本被制作。以这种方式使用 MemoryStream 的另一个问题是绕过缓存。执行此操作的最佳方法是使用 BitmapCacheOptions.OnLoad 直接从文件中读取:
此解决方案也高效且简单。
注意:如果您确实想绕过缓存,例如因为图像可能在磁盘上发生更改,则还应该设置 CreateOption = BitmapCreateOption.IgnoreImageCache。但即使在这种情况下,该解决方案的性能也优于
MemoryStream
解决方案,因为它不在 RAM 中保留图像数据的两个副本。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 theMemoryStream
you make one copy, and when the bitmap is decoded another copy is made. Another problem with usingMemoryStream
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:
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 theMemoryStream
solution because it doesn't keep two copies of the image data in RAM.在提供给 imagesource 之前将图像复制到 MemoryStream
它应该看起来像这样
,其中 byteStream 是 MemoryStream 中文件的副本
也是 this 可能有用
copy the image to MemoryStream before giving to imagesource
it should look like this
where byteStream is copy of file in MemoryStream
also this can be useful