Welcome to MSDN Blogs Sign in | Join | Help

Lester's WPF blog


Simple, easy & beautiful

News

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

 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
Posted: Thursday, March 08, 2007 4:50 PM by llester
Attachment(s): WindowsApplication1.zip

Comments

rickbrew said:

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

# March 8, 2007 4:55 PM

llester said:

thanks for pointing out the glitch :)

# March 8, 2007 9:44 PM

sridhsri said:

Thanks Les, this was the missing link for me

# March 22, 2007 2:03 PM
New Comments to this post are disabled
Page view tracker