1. 程式人生 > 其它 >C# bitmap轉換bitmapSource引發的記憶體洩漏

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