WPF bitmap转bitmapimage 使用 CreateBitmapSourceFromHBitmap内存泄漏

IntPtr f = bmp.GetHbitmap();
img.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(f, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

这里要是多次使用 不及时释放内存就会爆炸~

解决办法:

用windows下的GDI32.DLL类

使用办法:

先引用system.runtime.serialzation类

如果解决方案配置是在Debug下面的话

把gdi32.dll放在bingdebug

然后新建一个类

  static  class Class1
    {
      [System.Runtime.InteropServices.DllImport("gdi32.dll")]
      public static extern bool DeleteObject(IntPtr o);
    }

然后每次在转化以后 

  Class1.DeleteObject(f);

一下就好了

内存就不会爆炸了 


There are two ways of constructing a software design.One is to make it so simple that there are obviously no deficiencies;the other is to make it so complicated that there are no obvious deficiencies.
原文地址:https://www.cnblogs.com/yuanjunqq/p/5418872.html