C# System.Drawing Image to WPF BitmapImage
Posted By Mike Bender / 30th January 2012
I was recently presented with an issue of casting a Bitmap Image (System.Drawing.Image) to a BitmapImage (System.Windows.Media.Imaging). Unfortunately WPF has no converter for this. To solve this issue I created a helper function that utilizes the BitmapImage StreamSource property to write a System.Drawing.Image to the object. I’ve included the helper function in full below.
You are free to use this code in any form you wish.
using System.IO;
using System.Windows.Media.Imaging;
namespace System.Drawing
{
public static class ImageExtensions
{
///
/// Returns a BitmapImage from the passed bitmap.
///
/// Bitmap to convert.
///
public static BitmapImage ToBitmapImage(this Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, image.RawFormat);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
return bi;
}
}
}
Hopefully this helper makes your day a bit better!
Update:
When working with EDSDK see my post Canon EDSDK Liveview and Bitmap for details on working with the evfImg memory stream.