WPF CreateBitmapSourceFromHBitmap()的内存泄漏内存、WPF、CreateBitmapSourceFromHBitmap

由网友(红尘烟雨碎相思)分享简介:我需要通过像素绘制图像像素内的WPF显示。我试图通过做这一个 System.Drawing.Bitmap 然后用 CreateBitmapSourceFromHBitmap()来创建一个的BitmapSource $的WPF图像控件。我有内存泄漏的地方,因为当 CreateBitmapSourceFromBitmap...

我需要通过像素绘制图像像素内的WPF显示。我试图通过做这一个 System.Drawing.Bitmap 然后用 CreateBitmapSourceFromHBitmap()来创建一个的BitmapSource $的WPF图像控件。我有内存泄漏的地方,因为当 CreateBitmapSourceFromBitmap()反复调用的内存使用量上升,并且不落,直到应用程序结束。如果我不叫 CreateBitmapSourceFromBitmap()没有在内存使用量无明显变化。

I need to draw an image pixel by pixel and display it inside a WPF. I am attempting to do this by using a System.Drawing.Bitmap then using CreateBitmapSourceFromHBitmap() to create a BitmapSource for a WPF Image control. I have a memory leak somewhere because when the CreateBitmapSourceFromBitmap() is called repeatedly the memory usage goes up and does not drop off until the application is ended. If I don't call CreateBitmapSourceFromBitmap() there is no noticeable change in memory usage.

for (int i = 0; i < 100; i++)
{
    var bmp = new System.Drawing.Bitmap(1000, 1000);
    var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    source = null;
    bmp.Dispose();
    bmp = null;
}

我能做些什么,以释放的BitmapSource 内存?

推荐答案

MSDN指出,对于 Bitmap.GetHbitmap():你是负责调用GDI DeleteObject方法释放所使用的GDI的位图对象的内存的所以使用下面的code:

MSDN states that for Bitmap.GetHbitmap(): You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object. So use the following code:

// at class level
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

// your code
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1000, 1000)) 
{
    IntPtr hBitmap = bmp.GetHbitmap(); 

    try 
    {
        var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    }
    finally 
    {
        DeleteObject(hBitmap)
    }
}

我也由一个使用语句替换你的的Dispose()电话。

I also replaced your Dispose() call by an using statement.

阅读全文

相关推荐

最新文章