Friday, June 27, 2008
Converting GDI+ Images to WPF Bitmap Sources
Here is something I have shown as a little side-note at various conferences, and I have people sending me email about how I did it: Basically, this is about converting GDI+ Bitmap/Image objects to something WPF can consume. The trick is to convert the Image into BitmapSource objects, which can then be used on all kinds of WPF objects, such as images or brushes. Here is how to convert GDI+ Bitmaps into WPF BitmapSource objects:
Bitmap bmp = some bitmap...; // Replace with a real bitmap
BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
Sometimes, you may want to bind directly to a GDI+ bitmap object. In that case, you can create a ValueConverter object that does the conversion for you:
public class BitmapConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Converts a GDI bitmap to an image source
Bitmap bmp = value as Bitmap;
if (bmp != null)
{
BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
bmp.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
return bitmapSource;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
That's it! Not much to it...
Posted @ 2:28 PM by Egger, Markus (markus@code-magazine.com)