Render System.Drawing.Image in WPF

I’ve been working on a ViewModel style framework for a big project coming up at work, I decided to add a little spice to the test “Widget” and “Dirchie” objects by including an Image property that loads and saves to the database.

As it turns out it added plenty of spice as it’s not the easiest thing to pull off. Anyhow I eventually got the DB provider loading and saving a standard System.Drawing.Image object, only to find out you can’t actually use it natively in WPF.

Here’s the value converter I wrote to do the conversion for me (the code was adapted from this sample).

using System;
using System.Windows;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media.Imaging;
using System.Windows.Interop;
using System.Drawing;

namespace Qaf
    [ValueConversion(typeof(Image), typeof(BitmapSource))]
    public class ImageToBitmapSourceConverter : IValueConverter
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            Image val = (Image)value;

            Bitmap bitMap = new Bitmap(val);
            return Imaging.CreateBitmapSourceFromHBitmap(bitMap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            throw new InvalidOperationException("This should not be called");

Posted in C#

Leave a Reply

Your email address will not be published. Required fields are marked *