系统:Windows XP SP3,.NET 3.5,4GB RAM,双1.6gHz
我有一个WPF应用程序加载和转换(使用Storyboard动画)非常大的PNG.这些PNG的分辨率为8190x1080.当应用程序运行时,它似乎缓存图像,系统内存缓慢爬升.最终它会阻塞系统并抛出OutOfMemoryException.
以下是我目前正在尝试解决此问题的步骤:
1)我从应用程序中删除BitmapSource对象
2)我在加载BitmapSource时将BitmapSource BitmapCacheOption设置为None
3)我在加载后冻结BitmapSource.
4)我将删除对使用源的Image的所有引用以及对源本身的任何引用.
5)完成上述步骤后,手动调用GC.Collect().
希望找出为什么WPF挂在这些映像的内存上,以及确保用于加载它们的内存得到正确恢复的可能解决方案.
我一直在尝试序列化和反序列化BitmapImages.我一直在使用我认为在这个线程中找到的方法:我的byte []错误到WPF BitmapImage转换?
只是为了迭代正在发生的事情,这是我的序列化代码的一部分:
using (MemoryStream ms = new MemoryStream())
{
// This is a BitmapImage fetched from a dictionary.
BitmapImage image = kvp.Value;
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(ms);
byte[] buffer = ms.GetBuffer();
// Here I'm adding the byte[] array to SerializationInfo
info.AddValue((int)kvp.Key + "", buffer);
}
Run Code Online (Sandbox Code Playgroud)
这是反序列化代码:
// While iterating over SerializationInfo in the deserialization
// constructor I pull the byte[] array out of an
// SerializationEntry
using (MemoryStream ms = new MemoryStream(entry.Value as byte[]))
{ …Run Code Online (Sandbox Code Playgroud) 我正在尝试在XML 文件中保存和加载ImageSource(或BitmapSource)。快速浏览一下 SO 给了我这个答案。
看起来不错,所以我试了一下,但我得到了一个奇怪的结果。
当我尝试此代码时,一切正常:
BitmapSource testImgSrc = new WriteableBitmap(new BitmapImage(new Uri("pack://application:,,,/MyNameSpace;component/Images/MyImg.png")));
BackgroundImage = testImgSrc;
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这段代码时,图像根本没有出现:
BitmapSource testImgSrc = new WriteableBitmap(new BitmapImage(new Uri("pack://application:,,,/MyNameSpace;component/Images/MyImg.png")));
string testImgStr = ImageToBase64(testImgSrc);
BitmapSource testImg = Base64ToImage(testImgStr);
BackgroundImage = testImg;
Run Code Online (Sandbox Code Playgroud)
似乎没有任何错误或异常。当逐步执行代码时,BackgroundImage它看起来像是被设置为一个有效的图像对象。
我的 WPF 表单有一个图像控件,它的源代码绑定到一个返回属性结果的BackgroundImage属性。我猜绑定工作正常,因为第一个测试按预期工作。
谁能帮我理解为什么第二个测试没有显示我的图像?