WPF CreateBitmapSourceFromHBitmap() 内存泄漏 [英] WPF CreateBitmapSourceFromHBitmap() memory leak

查看:44
本文介绍了WPF CreateBitmapSourceFromHBitmap() 内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要逐个像素地绘制图像并将其显示在 WPF 中.我试图通过使用 System.Drawing.Bitmap 然后使用 CreateBitmapSourceFromHBitmap() 为 WPF Image 控件创建一个 BitmapSource 来做到这一点.我在某处发生内存泄漏,因为当重复调用 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 forBitmap.GetHbitmap() 状态:

备注

您负责调用 GDI DeleteObject 方法以释放 GDI 位图对象使用的内存.

You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object.

所以使用以下代码:

// 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);
    }
}

我还用 using 语句替换了您的 Dispose() 调用.

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

这篇关于WPF CreateBitmapSourceFromHBitmap() 内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆