user70192
user70192

Reputation: 14204

Load a byte[] into an Image at Runtime

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.

Upvotes: 12

Views: 17248

Answers (4)

Kevin B Burns
Kevin B Burns

Reputation: 1067

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.

Upvotes: 1

Jobi Joy
Jobi Joy

Reputation: 50038

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.

Upvotes: 21

Thomas Amar
Thomas Amar

Reputation: 362

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);
}

Upvotes: 1

configurator
configurator

Reputation: 41630

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

Upvotes: 5

Related Questions