Lester's WPF\SL Blog

Simple, Easy & Beautiful

BitmapSource-Bitmap interop

BitmapSource-Bitmap interop

Rate This
  • Comments 3

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

 unsafe

 {

      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(

                    bitmap.GetHbitmap(),

                    IntPtr.Zero,

                    Int32Rect.Empty,

System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

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
Attachment: WindowsApplication1.zip
  • 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!)

  • thanks for pointing out the glitch :)

  • Thanks Les, this was the missing link for me

Page 1 of 1 (3 items)