Partilhar via


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

WindowsApplication1.zip

Comments

  • Anonymous
    March 08, 2007
    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!)
  • Anonymous
    March 08, 2007
    thanks for pointing out the glitch :)

  • Anonymous
    March 22, 2007
    Thanks Les, this was the missing link for me