2011-12-29 117 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; 
}