Reputation: 133
I have am using a WPF application which uses BitmapSource but I need to do some manipulation but I need to do some manipulation of System.Drawing.Bitmaps.
The memory use of the application increases while it runs.
I have narrowed down the memory leak to this code:
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;
}
I assume it is the unmanaged memory not being disposed of properly, but I cannot seem to find anyway of doing it manually. Thanks in advance for any help!
Alex
Upvotes: 8
Views: 3284
Reputation: 3095
Are you releasing bitmap handle?
According to MSDN (http://msdn.microsoft.com/en-us/library/1dz311e4.aspx)
You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object. For more information about GDI bitmaps, see Bitmaps in the Windows GDI documentation.
Upvotes: 0
Reputation: 2377
The MSDN says You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object.. The following question deals with the same problem and there is already answer WPF CreateBitmapSourceFromHBitmap memory leak
Upvotes: 1
Reputation: 726479
You need to call DeleteObject(hBitmap)
on the 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;
}
Upvotes: 4
Reputation: 75296
You need to call DeleteObject(...)
on your hBitmap
. See: 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;
}
Upvotes: 10