12

I have a byte[] that is represented by an Image. I am downloading this Image via a WebClient. When the WebClient has downloaded the picture and I reference it using its URL, I get a byte[]. My question is, how do I load a byte[] into an Image element in WPF? Thank you.

Note: This is complementary to the question I asked here: Generate Image at Runtime. I cannot seem to get that approach to work, so I am trying a different approach.

Community
  • 1
  • 1
user70192
  • 13,786
  • 51
  • 160
  • 240
  • Please note, I am looking to load a byte[] into a System.Windows.Controls.Image instance. Not a System.Drawing.Image instance as everyone has kindly pointed out. – user70192 Feb 24 '09 at 20:14

4 Answers4

21

Create a BitmapImage from the MemoryStream as below:

MemoryStream byteStream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = byteStream;
image.EndInit();

And in XAML you can create an Image control and set the above image as the Source property.

Timo
  • 263
  • 3
  • 8
Jobi Joy
  • 49,102
  • 20
  • 108
  • 119
5

You can use a BitmapImage, and sets its StreamSource to a stream containing the binary data. If you want to make a stream from a byte[], use a MemoryStream:

MemoryStream stream = new MemoryStream(bytes);
configurator
  • 40,828
  • 14
  • 81
  • 115
1

One way that I figured out how to do it so that it was both fast and thread safe was the following:

 var imgBytes = value as byte[];
 if (imgBytes == null)
  return null;
 using (var stream = new MemoryStream(imgBytes))
   return BitmapFrame.Create(stream,BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

I threw that into a converter for my WPF application after running the images as Varbinary from the DB.

Kevin B Burns
  • 1,032
  • 9
  • 24
1

In .Net framework 4.0

using System.Drawing;
using System.Web;

private Image GetImageFile(HttpPostedFileBase postedFile)
{
   if (postedFile == null) return null;
   return Image.FromStream(postedFile.InputStream);
}
Thomas Amar
  • 352
  • 10
  • 20