C# bitmap转换bitmapSource引发的内存泄漏
原代码:
private BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap src)
{
IntPtr ip = src.GetHbitmap();//从GDI+ Bitmap创建GDI位图对象
BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
return bitmapSource;
}
修改后代码:
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
private BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap src)
{
IntPtr ip = src.GetHbitmap();//从GDI+ Bitmap创建GDI位图对象
BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
DeleteObject(ip);//释放IntPtr,不然会引发内存泄漏
return bitmapSource;
}
或者将bitmap转换为bitmapimage也可以
private BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap src)
{
MemoryStream ms = new MemoryStream();
src.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bt = new BitmapImage();
bt.BeginInit();
bt.StreamSource = ms;
bt.EndInit();
return bt;
}

浙公网安备 33010602011771号