Bitmap 转换为 ImageSource
[DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteObject(IntPtr hObject);
/// <summary>
/// 将 Bitmap 转换为 ImageSource
/// 使用过System.Drawing.Bitmap后一定要用DeleteObject释放掉对象,不然内存不释,很快系统内存就消耗光了。
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public static ImageSource ToImageSource(this Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(hBitmap,IntPtr.Zero,Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());
// 记得要进行内存释放。否则会有内存不足的报错。
if (!DeleteObject(hBitmap))
{
Basic._logger.Error("内存释放错误!");
throw new Win32Exception();
}
return wpfBitmap;
}