我正在尝试操作图像,当涉及到位图和图像时,我是相当新的,所以我的问题和代码都是如此。我正在初始化一个字节数组来保存 Bgr24 像素数据,这样我就可以将它传递到 BitmapSource 对象中。但是我的像素阵列不是“我认为”的正确尺寸。
最后一行代码实际上是我的问题所在,参数“pixels”向我抛出以下错误“System.ArgumentException was unhandled Value does not fall in the expected range.”
我初始化这些变量
int imageSize = 100;
double dpi = 96;
int width = 128;
int height = 128;
byte[] pixels = new byte[width * height * 3];
//Create my image....
for (int i = 0; i < imageSize; i++)
{
for (int j = 0; j < imageSize; j++)
{
int ct = myImage[i, j];
pixels[i * imageSize * 3 + j + 0] = (byte)((ct % 16) * 14);
pixels[i * imageSize * 3 + j + 1] = (byte)((ct % 32) * 7);
pixels[i * imageSize * 3 + j + 2] = (byte)((ct % 128) * 2);
}
}//end for
//Create the bitmap
BitmapSource bmpSource = BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgr24, null, pixels, width);
我知道我没有正确设置像素阵列。有什么想法吗?
请您参考如下方法:
“值不在预期范围内”是当 WIC 函数(WPF 成像功能底层的 native API)返回 WINCODEC_ERR_INVALIDPRAMETER< 时 .HRESULT.Check 抛出的 ArgumentException 消息
在这种情况下,问题在于 BitmapSource.Create 的最终参数应该是位图的“跨度”(不是 宽度)。位图的“跨度”是存储位图的每一行所需的(整数)字节数。根据 this MSDN magazine article ,计算步幅的一般公式是stride = (width * bitsPerPixel + 7)/8;。对于 24bpp 位图,这简化为 width * 3。
为防止异常,请传入正确的步幅值:
BitmapSource bmpSource = BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgr24, null, pixels, width * 3);
