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

标签 c# wpf pixel bitmapsource

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

最佳答案

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;
}

关于c# - BitmapSource.CopyPixels->byte[]->BitmapSource 怎么做这个简单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8311805/

相关文章:

c# - 如何将接口(interface)的具体实现传递到接受泛型接口(interface)的 MVC 局部 View 中?

c# - WPF ListView : Set the Background color for specific items when Focusable is set to false

c++ - 如何将像素缓冲区复制到更大的缓冲区

c# - 从 C# 代码调用 dll 函数期间出错

c# - ASP.NET 5 (vNext) 中的身份验证

c# - Visual Studio 社区版中的连接字符串

c# - 将 WPF 控件绑定(bind)到 Timer 中更新的数据是否安全?

wpf - 在 WPF 中显示和编辑二维数组的最佳方式

python - 画一条几乎直线

c++ - 使用opencv循环像素