Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitmapSource.CopyPixels->byte[]->BitmapSource how to do this simple?

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

like image 523
curiousity Avatar asked Sep 18 '25 15:09

curiousity


1 Answers

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;
}
like image 118
Miro Bucko Avatar answered Sep 20 '25 06:09

Miro Bucko