WPF使用Image控件显示Bitmap

在WPF中,Image控件不支持Bitmap类型,但支持ImageSource类型,因此需要进行类型转换。

转换类:

public static class BitmapSourceConvert

{

    /// 

    /// Delete a GDI object

    /// 

    ///  name="o">The poniter to the GDI object to be deleted

    /// 

    [DllImport("gdi32")]

    private static extern int DeleteObject(IntPtr o);

    /// 

    /// Convert an Bitmap to a WPF BitmapSource. The result can be used in the Set Property of Image.Source

    /// 

    ///  name="image">Bitmap

    /// The equivalent BitmapSource

    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);

你可能感兴趣的:(C#图像处理)