I have a memory leak issue in my application which loads a large amount of images. I\'m rather new to C#, and thought my days of memory leak issues were past. I can\'t figur
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;
}