How can I convert byte[] to BitmapImage?

后端 未结 4 848
死守一世寂寞
死守一世寂寞 2021-01-17 12:03

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

4条回答
  •  死守一世寂寞
    2021-01-17 12:24

    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 bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8;
    var stride = bytesPerPixel * width;
    
    var bitmap = BitmapSource.Create(width, height, dpiX, dpiY,
                                     pixelFormat, null, buffer, stride);
    

提交回复
热议问题