Thursday, April 28, 2011

Convert from System.Drawing.Image to System.Windows.Controls.Image

I was struck with the problem of converting a System.Drawing.Image type Image to System.Windows.Controls.Image. It was very difficult to find relevant resources on the Internet. So I thought of sharing the method for the benefits of everyone.

It works perfectly for me!!.

private System.Windows.Controls.Image ConvertDrawingImageToWPFImage(System.Drawing.Image gdiImg)

System.Windows.Controls.Image img = new System.Windows.Controls.Image();

//convert System.Drawing.Image to WPF image
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(gdiImg);
IntPtr hBitmap = bmp.GetHbitmap();
System.Windows.Media.ImageSource WpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

img.Source = WpfBitmap;
img.Width = 500;
img.Height = 600;
img.Stretch = System.Windows.Media.Stretch.Fill;
return img;


Ford said...

I was looking for a method to convert between these image types, and fit my needs perfectly. Thanks for sharing!

My next option would have been to save the system.drawing.image to a temp file, then load it from file as a

Anonymous said...

Thanks for sharing :-) It really helped!

Anonymous said...

how to convert wpf Image to gdi Image

Anonymous said...

Thanks a lot!

Anonymous said...

oh ! thank you man I was like a crazy finding this

Anonymous said...

Thank you men!!

IƱigo Panera said...

Thanks. Very useful!!
Only one issue.
I had to change this lines:
img.Width = 500;
img.Height = 600;
with this:
img.Width = gdiImg.Width;
img.Height = gdiImg.Height;
to be able to adjust dynamcaly the image resolution

Abel Beneberu said...

tnx !!