Image loading memory leak with C#

时光总嘲笑我的痴心妄想 提交于 2019-11-28 09:16:56

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!