2011-12-29 115 views
7

我有使用WPF应用程序使用BitmapSource但我需要做一些操作 但我需要做一些操作System.Drawing.Bitmaps。非托管内存泄漏

运行时应用程序的内存使用量增加。

我有内存泄漏缩小到这样的代码:

private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap) 
{ 
      BitmapSource bms; 
      IntPtr hBitmap = bitmap.GetHbitmap(); 
      BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions(); 
      bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions); 
      bms.Freeze(); 
      return bms; 
} 

我认为它是没有被妥善处理非托管的内存,但我似乎无法找到反正做手工的。预先感谢任何帮助!

亚历

+0

的可能重复[WPF CreateBitmapSourceFromHBitmap内存泄漏(http://stackoverflow.com/questions/1546091/wpf-createbitmapsourcefromhbitmap-memory-leak) – Pieniadz 2014-05-28 08:59:53

回答

9

你需要调用DeleteObject(...)hBitmap。请参阅:http://msdn.microsoft.com/en-us/library/1dz311e4.aspx

private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap) 
{ 
    BitmapSource bms; 
    IntPtr hBitmap = bitmap.GetHbitmap(); 
    BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions(); 
    bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, 
     IntPtr.Zero, Int32Rect.Empty, sizeOptions); 
    bms.Freeze(); 

    // NEW: 
    DeleteObject(hBitmap); 

    return bms; 
} 
+3

我正要恰好写了同样的答案;) 这里的'DeleteObject'方法的声明: '[DllImport(“gdi32.dll”)] static extern bool DeleteObject(IntPtr hObject);' – ken2k 2011-12-29 16:11:37

+0

@ ken2k:我正要添加完全相同的声明。谢谢! – MusiGenesis 2011-12-29 16:13:38

+0

非常感谢,解决了我的问题! – aforward 2011-12-29 16:33:16

4

你需要调用DeleteObject(hBitmap)的HBITMAP:

private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap) { 
     BitmapSource bms; 
     IntPtr hBitmap = bitmap.GetHbitmap(); 
     BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions(); 
     try { 
      bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions); 
      bms.Freeze(); 
     } finally { 
      DeleteObject(hBitmap); 
     } 
     return bms; 
}