BitmapSource-Bitmap interop

Recently I was trying my hand at a rough image editing scenario and one of the things was changing into gray scale, brightness and so forth. If you have played with .NET 2.0 you get quite a few functions which help in these types of operations and it would be nice shifting Images to Bitmaps and vice versa.  As luck would have it, Robert had posted some code on this in the forums.

To get the Bitmap you would have to call CopyPixels on the BitmapSource and convert it to a Bitmap-

transformedBitmapSource.CopyPixels(bits, stride, 0);



      fixed (byte* pBits = bits)


          IntPtr ptr = new IntPtr(pBits);

          System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(

width,height,stride,                            System.Drawing.Imaging.PixelFormat.Format32bppPArgb,ptr);

            return bitmap;



To do the reverse:

System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(





WPFImage.Source = bitmapSource;

These functions are pretty handy if you are doing something like the below:


The sample project along with the functions is attached.

Share this post

Comments (3)
  1. rickbrew says:

    Watch out though:

    1) The call to GetHbitmap() will leave a dangling GDI handle unless you P/Invoke to DeleteObject(). (The docs state this!)

    2) CreateBitmapSourceFromHBitmap() makes a copy of the GDI bitmap. I have yet to find a way to alias a WPF bitmap on to a GDI/GDI+ bitmap, or vice versa. And from talking with the WPF guys, this just isn’t possible 🙁 (I really need it for some Paint.NET stuff I want to do!)

  2. thanks for pointing out the glitch 🙂

  3. sridhsri says:

    Thanks Les, this was the missing link for me

Comments are closed.

Skip to main content