How to give System.Drawing.Image data to System.Windows.Media.ImageSource (WPF) to display? RRS feed

  • Question

  • Hi,

    Can i get help on how to or can we give System.Drawing.Image data to a System.Windows.Media.ImageSorce in WPF/Xaml.

    Basically I'm trying to display list of controls in my WPF application toolbox having images/icons in respective ToolboxBitmapAttribute . GetImage() method of ToolboxBitmapAttribute class gives me back a System.Drawing.Image, which cannot be directly set to System.Windows.Media.ImageSource. And that's the problem.

    I do have an alternative ( or a hack  ) by writing the image to a file on the disk and give that path to my ImageSource (Yes, My application is a windows/desktop based application). But it looks like a desperate move and I don't want to do that.

    Any better or correct way would really help. Thank You.


    Thursday, November 8, 2007 6:40 PM


  • Hi Anil,

    I answered a similar question yesterday... I dont know if there's a better way to do it, but you can make it a bit less hacky (and far more performant) by writing the image to a memory stream and not the file system.  The performance seems totally acceptable for the scenario I tried.  You'd want to do something like:




    // Winforms Image we want to get the WPF Image from...

    System.Drawing.Image imgWinForms = System.Drawing.Image.FromFile("test.png");


    // ImageSource ...

    BitmapImage bi = new BitmapImage();


    MemoryStream ms = new MemoryStream();

    // Save to a memory stream...

    imgWinForms.Save(ms, ImageFormat.Bmp);

    // Rewind the stream...

    ms.Seek(0, SeekOrigin.Begin);

    // Tell the WPF image to use this stream...

    bi.StreamSource = ms;




    HTH.  Let me know if you figure out something less hacky, I'd love to know since this question has come up more than once...







    Thursday, November 8, 2007 6:46 PM
  •   This question has been answered here:




    Monday, November 12, 2007 9:56 AM

All replies