Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert byte[] to BitmapImage?

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.

like image 584
gerstla Avatar asked Mar 07 '13 12:03

gerstla


People also ask

How do you get a byte from a string?

Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .

What is Bytearray?

A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.


2 Answers

When your byte array contains a bitmap's raw pixel data, you may create a BitmapSource (which is the base class of BitmapImage) by the static method BitmapSource.Create.

However, you need to specify a few parameters of the bitmap. You must know in advance the width and height and also the PixelFormat of the buffer.

byte[] buffer = ...;

var width = 100; // for example
var height = 100; // for example
var dpiX = 96d;
var dpiY = 96d;
var pixelFormat = PixelFormats.Pbgra32; // for example
var stride = (width * pixelFormat.BitsPerPixel + 7) / 8;

var bitmap = BitmapSource.Create(width, height, dpiX, dpiY,
                                 pixelFormat, null, buffer, stride);
like image 66
Clemens Avatar answered Sep 22 '22 10:09

Clemens


The code below does not create a BitmapSource from a raw pixel buffer, as asked in the question.

But in case you want to create a BitmapImage from an encoded frame like a PNG or a JPEG, you would do it like this:

public static BitmapImage LoadFromBytes(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.StreamSource = stream;
        image.EndInit();

        return image;
    }
}
like image 35
Eirik Avatar answered Sep 19 '22 10:09

Eirik