Fortunately, Microsoft provide a nice little Interop method for this. Unfortunately, it's not that useful by itself.
The following .NET 3.5 extension methods convert either a System.Drawing.Image or System.Drawing.Bitmap to a System.Windows.Media.Imaging.BitmapSource.
////// Contains extension methods for images. /// public static class ImageExtensions { ////// Converts a /// The source image.///into a . /// A public static BitmapSource ToBitmapSource(this System.Drawing.Image source) { System.Drawing.Bitmap bitmap = source as System.Drawing.Bitmap; if (bitmap != null) return bitmap.ToBitmapSource(); bitmap = new System.Drawing.Bitmap(source); try { return bitmap.ToBitmapSource(); } finally { bitmap.Dispose(); } } ///containing the same image. /// Converts a /// The source bitmap.///into a . /// /// Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject. /// ///A public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source) { var hBitmap = source.GetHbitmap(); try { return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } catch (Win32Exception) { return null; } finally { NativeMethods.DeleteObject(hBitmap); } } }containing the same image.
Enjoy!
No comments:
Post a Comment