BitmapSource.CopyPixels-> byte [] - > BitmapSource怎么做这么简单?

时间:2011-11-29 13:48:13

标签: c# wpf pixels bitmapsource

如何在C#中有效地将BitmapSource转换为byte [],反之亦然?

1 个答案:

答案 0 :(得分:10)

BitmapSource到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 []到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;
}
相关问题