2011-12-29 5 views
7

BitmapSource를 사용하는 WPF 응용 프로그램을 사용하고 있지만 일부 조작을 수행해야합니다. 하지만 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

답변

9

당신은 당신의 hBitmapDeleteObject(...)를 호출해야합니다. 참조 : 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

는 I 똑같은 대답을 작성하고 있었다) 여기에있어 DeleteObject' 메소드의 선언 : '[DllImport ("gdi32.dll")] static Extern bool DeleteObject (IntPtr hObject); ' – ken2k

+0

@ ken2k : 정확히 동일한 선언을 추가하려고합니다. 감사! – MusiGenesis

+0

대단히 고마워, 그게 내 문제를 해결해 줬어! – aforward

4

당신은 HBITMAP에 DeleteObject(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; 
} 
0

비트 맵 핸들을 해제 하시겠습니까? MSDN 당신은 GDI 비트 맵 객체에 의해 사용되는 메모리를 확보 할 수있는 GDI DeleteObject 매크로 메서드를 호출 할 책임이 있습니다

(http://msdn.microsoft.com/en-us/library/1dz311e4.aspx)에 따르면

. GDI 비트 맵에 대한 자세한 내용은 Windows GDI 설명서의 비트 맵을 참조하십시오.