4

How to do efficient BitmapSource to byte[] and vice versa conversion in C#?

Miro Bucko
  • 1,123
  • 1
  • 13
  • 26
curiousity
  • 4,703
  • 8
  • 39
  • 59

1 Answers1

11

BitmapSource to byte[]:

private byte[] BitmapSourceToArray(BitmapSource bitmapSource)
{
    // Stride = (width) x (bytes per pixel)
    int stride = (int)bitmapSource.PixelWidth * (bitmapSource.Format.BitsPerPixel / 8);
    byte[] pixels = new byte[(int)bitmapSource.PixelHeight * stride];

    bitmapSource.CopyPixels(pixels, stride, 0);

    return pixels;
}

byte[] to BitmapSource:

private BitmapSource BitmapSourceFromArray(byte[] pixels, int width, int height)
{
    WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);

    bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * (bitmap.Format.BitsPerPixel / 8), 0);

    return bitmap;
}
Miro Bucko
  • 1,123
  • 1
  • 13
  • 26
  • 5
    Attention: Using `width * (bitmap.Format.BitsPerPixel / 8)` will not work in all scenarios. There are several pixel formats with less than 8 bits per pixel. A correct rounding up could be achieved using `width * (bitmap.Format.BitsPerPixel + 7) / 8` –  Aug 12 '15 at 08:30
  • 1
    Can also use [BitmapSource.Create](https://msdn.microsoft.com/en-us/library/ms616045(v=vs.110).aspx) to go from byte[] to BitmapSource. – Ron Woods Jul 14 '16 at 20:39