BitmapSource.Create 值超出范围

Value out of range with BitmapSource.Create

正在使用 WPF 并尝试从头开始创建 BitmapSource。以下代码给出了一个参数异常“值不在预期范围内。”我不知道为什么。我还是 WPF 的新手,也许我没有正确使用像素格式?

int width = 12;
int height = 14;
byte[] colorData = new byte[width * height * 4];
for(int i = 0; i < colorData.Length; i++)
{
    colorData[i] = 155;  //create all pixels same shade of gray
}
BitmapSource bitmap = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, colorData, width);

BitmapSource.Create方法的最后一个参数是步长,即每"scan line".

的字节数

对于每个像素有四个字节的像素格式,它是 4 * width:

var stride = 4 * width;
var bitmap = BitmapSource.Create(
    width, height, 96, 96, PixelFormats.Bgra32, null, colorData, stride);