问题描述
我正在使用 C# WPF 开发一个图片库应用程序,当 BitmapImages 不再需要/未使用时,我在清理它们时遇到了问题。
我正在使用自己的图像类,其中包含名称、路径和一些附加数据,但最重要的是 BitmapImage 本身。
在图库中,一个列表框(显示图像数据以及图像本身)充满了图像。这里的图片已经有缩略图大小,所以不需要调整大小。
当所选列表框项更改时,将全局
在要预览的图像之间切换时,“旧”BitmapImage 似乎没有从内存中删除,并且随着 CurrentimageObject 的不断更新而不断增加。
CurrentimageObject = (Resources.Image)ListBoxImages.SelectedItem;
CurrentimageObject.Img = new BitmapImage();
using (FileStream fs = File.Open(CurrentimageObject.Path,FileMode.Open,FileAccess.Read))
{
CurrentimageObject.Img.BeginInit();
CurrentimageObject.Img.CacheOption = BitmapCacheOption.OnLoad;
CurrentimageObject.Img.StreamSource = fs;
CurrentimageObject.Img.EndInit();
}
CurrentimageObject.Img.Freeze();
ImagePreview.source = CurrentimageObject.Img;
ImagePreview.UpdateLayout();
Memory usage when switching between previewed images
我面临的问题是,我不能真正利用 DecodePixelWidth / DecodePixelHeight 来保持 BitmapImage 的大小,因为我需要全尺寸的图像进行恢复,因为图像可以编辑,但也需要可以恢复。
有什么方法可以更新BitmapImage的StreamSource并删除其“旧”源,与图像本身的“旧”源相同。
或者,是否有更好的方法在编辑后恢复图像本身。目前,它的工作原理如下:
BitmapEncoder be = new JpegBitmapEncoder();
be.Frames.Add(BitmapFrame.Create(CurrentimageObject.Img));
using (var fs = new FileStream(CurrentimageObject.Path,FileMode.Create))
be.Save(fs);
编辑:我发现了增加内存的问题。 CurrentimageObject 只是对象的浅拷贝,因此 BitmapImage 更新了两次。
我必须在我的 Image 类中实现 Clone() 方法并添加 ICloneable 接口以使 CurrentimageObject 成为深层副本。
CurrentimageObject = ((Resources.Image)ListBoxImages.SelectedItem).Clone() as Resources.Image;
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)