I have a byte[]
that is represented by an Image
. I am downloading this Image
via a WebClient
. When the WebClient
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);
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.
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.
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);
}