tags:

views:

998

answers:

1

I'm trying to make my C# code add an image to my (WPF) application's canvas. However, my code does not work.

Image I = new Image();
I.Source = System.IO.File.Open(@"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg", System.IO.FileMode.Open);

I get the error:

Cannot implicitly convert type 'System.IO.FileStream' to 'System.Windows.Media.ImageSource'

I see why this is: The Image object wants the raw bitmap (or jpg or whatever), and my code is giving it an output stream from the file. How do I convert between the two?

+2  A: 

Approximately:

Image I = new Image();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(@"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg", UriKind.Absolute);
bi.EndInit();
I.Source = bi;
Jason
BitmapImage has a constructor overload that accepts a Uri. Would using that be any different than your example?
YotaXP
What do I need to import to make this work? At the moment Visual Studio compains, saying "'System.Windows.Controls.Image' does not contain a definition for 'FromStream'"
Sorry, I confounded System.Drawing.Image and System.Windows.Controls.Image when I made a revision to this post this morning. I rolled back to a correct solution.
Jason