在WPF中,Image控件不支持Bitmap类型,但支持ImageSource类型,因此需要进行类型转换。
转换类:
public static class BitmapSourceConvert
{
/// <summary>
/// Delete a GDI object
/// </summary>
/// <param name="o">The poniter to the GDI object to be deleted</param>
/// <returns></returns>
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
/// <summary>
/// Convert an Bitmap to a WPF BitmapSource. The result can be used in the Set Property of Image.Source
/// </summary>
/// <param name="image">Bitmap</param>
/// <returns>The equivalent BitmapSource</returns>
public static BitmapSource ToBitmapSource(System.Drawing.Bitmap image)
{
IntPtr ptr = image.GetHbitmap();//obtain the Hbitmap
BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap
(
ptr,
IntPtr.Zero,
Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()
);
DeleteObject(ptr);//release the HBitmap
return bs;
}
}
显示时使用如下代码:
bitmap = new System.Drawing.Bitmap("imageFile.jpg");
imageDisp.Source = BitmapSourceConvert.ToBitmapSource(bitmap);