0
点赞
收藏
分享

微信扫一扫

WPF Bitmap转imagesource

盖码范 2022-03-12 阅读 77
C#WPF


因为WPF中不支持直接显示bitmap格式图片,因此需要对bitmap转换成imagesource再显示。

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());

if (!DeleteObject(hBitmap))
{
throw new System.ComponentModel.Win32Exception();
}
return wpfBitmap;
}


需要及时释放hBitmap,否则内存会很快占满。


时间会记录下一切。


举报

相关推荐

0 条评论