Image loading memory leak with C#
When you call
bmp.GetHbitmap()
a copy of the bitmap is created. You'll need to keep a reference to the pointer to that object and call
DeleteObject(...)
on it.
From here:
Remarks
You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object.
You may be able to save yourself the headache (and overhead) of copying the bitmap by using BitmapImage instead of BitmapSource. This allows you to load and create in one step.
You need to call the GDI DeleteObject
method on the IntPtr
pointer returned from GetHBitmap(). The IntPtr
returned from the method is a pointer to the copy of the object in memory. This must be manually freed using the following code:
[System.Runtime.InteropServices.DllImport("gdi32.dll")]public static extern bool DeleteObject(IntPtr hObject);private static BitmapSource LoadImage(string path){ BitmapSource source; using (var bmp = new Bitmap(path)) { IntPtr hbmp = bmp.GetHbitmap(); source = Imaging.CreateBitmapSourceFromHBitmap( hbmp, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(hbmp); } return source;}
It seems that when you call GetHBitmap() you are responsible for freeing the object
[System.Runtime.InteropServices.DllImport("gdi32.dll")]public static extern bool DeleteObject(IntPtr hObject);private void DoGetHbitmap() { Bitmap bm = new Bitmap("Image.jpg"); IntPtr hBitmap = bm.GetHbitmap(); DeleteObject(hBitmap);}
I'm guessing that the BitmapSource doesn't take responsibility for freeing this object.