How can I convert byte[] to BitmapImage?

gerstla picture gerstla · Mar 7, 2013 · Viewed 16.6k times · Source

I have a byte[] that represents the raw data of an image. I would like to convert it to a BitmapImage.

I tried several examples I found but I kept getting the following exception

"No imaging component suitable to complete this operation was found."

I think it is because my byte[] does not actually represent an Image but only the raw bits. so my question is as mentioned above is how to convert a byte[] of raw bits to a BitmapImage.

Answer

Eirik picture Eirik · Mar 7, 2013
public static BitmapImage LoadFromBytes(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        stream.Seek(0, SeekOrigin.Begin);
        var image = new BitmapImage();
        image.BeginInit();
        image.StreamSource = stream;
        image.EndInit();

        return image;
    }
}