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

    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 08, 2007 6:40 PM

Answers

  • 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();

    bi.BeginInit();

    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;

    bi.EndInit();

     

     

    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...

     

    -Matt

     

     

     

     

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

          http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2387391&SiteID=1

     

     

    Monday, November 12, 2007 9:56 AM

All replies