[转][好用]-WPF Image转换为ImageSource

转自:http://www.wxzzz.com/1410.html,稍加修改。

[DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteObject(IntPtr hObject);

//将 Bitmap转换为BitmapSource
//使用过System.Drawing.Bitmap后一定要用DeleteObject释放掉对象,不然内存不释放,很快系统内存就消耗光了。
public static BitmapSource fun_BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
BitmapSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
if (!DeleteObject(hBitmap))//记得要进行内存释放。否则会有内存不足的报错。
{
throw new System.ComponentModel.Win32Exception();
}

return wpfBitmap;
}

posted @ 2017-08-16 16:27  percent10  阅读(729)  评论(0编辑  收藏  举报