WPF循环加载图片导致内存溢出如何解决2015-01-01程序场景:一系列的图片,从第一张到最后一张依次加载图片,形成“动画”。生成BitmapImage的方法有多种:1、var source=new BitmapImage(new Uri("图片路径",UriKind.xxx));一般的场景使用这种方法还是比较方便快捷,但是对于本场景,内存恐怕得爆。2、var data =File.ReadAllBytes("图片路径");var ms = new System.IO.MemoryStream(data);
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;
source.StreamSource = ms;
source.EndInit();
source.Freeze();
ms.Close();
return source;此方法基本可行,但有时也会不灵光,例如在调用高清摄像头的时候。高清的摄像头一般都会提供SDK,可以获取到图像数据byte[],使用以上的方法有可能还会导致内存溢出。可以使用以下这种方法试试://用Bitmap来转换,可以删除Bitmap的句柄来释放资源
var ms = new System.IO.MemoryStream(data);
var bmp = new System.Drawing.Bitmap(ms);
var source = ToBitmapSource(bmp);
ms.Close();
bmp.Dispose();
return source;
[DllImport("gdi32.dll", SetLastError = true)] private static extern bool DeleteObject(IntPtr hObject);private BitmapSource ToBitmapSource(System.Drawing.Bitmap bmp) { try { var ptr = bmp.GetHbitmap(); var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( ptr, IntPtr.Zero, Int32Rect.Empty,System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); DeleteObject(ptr); return source; } catch { return null; } }