Sunday, September 09, 2007

How to use ImageSource (no handler) in WinForms as System.Drawing.Bitmap (hbitmap)

How to easily convert WinForms System.Drawing.Bitmap into WPF ImageSource you learned from this article. Today, I'll explain how to do it contrary. Actually, all he have to do is to extract handler from BitmapSource, however, such approach is not supported, thus the only thing we can do is just copy pixels of BitmapSource (or BitmapFrame) into byte array and then copy them into the pointer of HBitmap. Here the code

 

public static System.Drawing.Bitmap BitmapSourceToBitmap(BitmapSource srs)

{


System.Drawing.
Bitmap btm = null;

int width = srs.PixelWidth;

int height = srs.PixelHeight;

int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);




byte[] bits = new byte[height * stride];




srs.CopyPixels(bits, stride, 0);





unsafe

{

fixed (byte* pB = bits)

{





IntPtr ptr = new IntPtr(pB);




btm =
new System.Drawing.Bitmap(

width,


height,


stride,


System.Drawing.Imaging.
PixelFormat.Format32bppPArgb,

ptr);





}


}


return btm;

}


 






Not so straight forward, but it works.



Source code for this article.

No comments: