How to load Bitmap image to Image object in WPF

No.of Views1976
Bookmarked0 times
Downloads 
Votes0
By  Prabu   On  25 Jun 2010 09:06:48
Tag : WPF , Image Handling
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
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

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.

CodeSnippet

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

 I hope this snippet to help to you all.

 
Sign Up to vote for this article
 
About Author
 
Prabu
Occupation-Software Engineer
Company-
Member Type-Fresh
Location-India
Joined date-23 Jun 2010
Home Page-
Blog Page-http://prabu-guru.blogspot.com/
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top