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