WPF

C# System.Drawing Image to WPF BitmapImage

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.

 

Related Posts:

  • No Related Posts

Project: multi-touch table

This post is the first of what should be many to come. I have decided to put a project that I have long had on hold (2 years or so). I am going to build a multi-touch table like the Microsoft Surface for myself. I have long read on this product and dreamed to have one, but alas I just don’t have $12,000 laying around to drop on one of these. Being a bit of a DIYer I have decided to take up the journey that many have and build my own!

Read Full Post »

Related Posts: