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

9 בספטמבר 2007

אין תגובות

[This blog was migrated. You will not be able to comment here.
The new URL of this post is http://khason.net/blog/how-to-use-imagesource-no-handler-in-winforms-as-systemdrawingbitmap-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.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *