Friday, May 14, 2010

How to load Bitmap image to Image object in WPF

I am doing an application (which I am converting Windows forms 2.0 application into WPF application for rich look) in WPF and I am need of the load the Image from an instance of a System.Drawing.Bitmap. Initially I was struggled to do this. After a few minutes of search in goggle, I found the following solution. With help of Imaging class, we can create a BitmapSource and assign the BitmapSource value to the Image. The following code will help you to do this.

    public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
    {
        BitmapSource bitmapSrc = null;
        var hBitmap = source.GetHbitmap();
        try
        {
            bitmapSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
        catch (Win32Exception)
        {
            bitmapSrc = null;
        }  
        finally
        {
            NativeMethods.DeleteObject(hBitmap);
        }
        return bitmapSrc;
    }

    internal static class NativeMethods
    {
        [DllImport("gdi32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool DeleteObject(IntPtr hObject);
    }

Please check this link for more details.

No comments: