方法1:
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(image);
IntPtr hBitmap = bmp.GetHbitmap();
System.Windows.Media.ImageSource WpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
box.Source = WpfBitmap;
方法2:
[System.Runtime.InteropServices.DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
//Bitmap转BitmapSource
public BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap bitMap)
{
//System.Drawing.Bitmap newBitMap = CaptureBitmapFormBitMap(bitMap, new System.Drawing.Rectangle(0, 0, bitMap.Width, bitMap.Height));
IntPtr ip = bitMap.GetHbitmap();
BitmapSource bitmapSource = null;
bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ip, IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromWidthAndHeight(bitMap.Width, bitMap.Height));
DeleteObject(ip);
return bitmapSource;
}
方法1是网上的,方法2是个人总结的,亲测都可以使用。
本文介绍了两种将System.Drawing.Bitmap转换为WPF中使用的BitmapSource的方法。方法一使用GetHbitmap()获取句柄并直接创建BitmapSource;方法二通过自定义函数BitmapToBitmapSource实现转换,并在完成后释放资源。
2455

被折叠的 条评论
为什么被折叠?



