为什么BitmapSource.Create引发ArgumentException? [英] Why does BitmapSource.Create throw an ArgumentException?
问题描述
我想从原始数据创建了一个位图WPF中显示,通过使用图像和的BitmapSource:
I'm trying to get an bitmap created from raw data to show in WPF, by using an Image and a BitmapSource:
Int32[] data = new Int32[RenderHeight * RenderWidth];
for (Int32 i = 0; i < RenderHeight; i++)
{
for (Int32 j = 0; j < RenderWidth; j++)
{
Int32 index = j + (i * RenderHeight);
if (i + j % 2 == 0)
data[index] = 0xFF0000;
else
data[index] = 0x00FF00;
}
}
BitmapSource source = BitmapSource.Create(RenderWidth, RenderHeight, 96.0, 96.0, PixelFormats.Bgr32, null, data, 0);
RenderImage.Source = source;
然而,呼吁BitmapSource.Create引发ArgumentException,说:值没有在预期的范围内。这难道不是这样做的方式吗?我不能作出这一呼吁是否正确?
However the call to BitmapSource.Create throws an ArgumentException, saying "Value does not fall within the expected range". Is this not the way to do this? Am I not making that call properly?
推荐答案
您步幅不正确。步幅被分配用于所述一个扫描线的字节数
位图。这样,使用以下命令:
Your stride is incorrect. Stride is the number of bytes allocated for one scanline of the bitmap. Thus, use the following:
int stride = ((RenderWidth * 32 + 31) & ~31) / 8;
和替换最后一个参数(目前为 0
)使用步幅
如上定义。
and replace the last parameter (currently 0
) with stride
as defined above.
下面是神秘的步幅公式的解释:
Here is an explanation for the mysterious stride formula:
事实:Scanlines的必须在32位边界(参考)对齐
Fact: Scanlines must be aligned on 32-bit boundaries (reference).
每扫描线的字节数天真的公式将是:
The naive formula for the number of bytes per scanline would be:
(width * bpp) / 8
但是,这可能不会给我们一个32位的边界上对齐位图(宽* BPP)甚至可能没有被8整除了
But this might not give us a bitmap aligned on a 32-bit boundary and (width * bpp) might not even have been divisible by 8.
所以,我们做的是我们强迫我们的位图在一排至少有32位(我们假设宽度大于0
)
So, what we do is we force our bitmap to have at least 32 bits in a row (we assume that width > 0
):
width * bpp + 31
,然后我们说我们不关心的低位(位0--4),因为我们正试图在32位边界对齐:
and then we say that we don't care about the low-order bits (bits 0--4) because we are trying to align on 32-bit boundaries:
(width * bpp + 31) & ~31
和再除以8要回字节:
((width * bpp + 31) & ~31) / 8
的填充可以通过
int padding = stride - (((width * bpp) + 7) / 8)
天真的公式将是
stride - ((width * bpp) / 8)
但宽* BPP
可能不是一个字节边界上对齐,当它没有这个公式将在未来数由一个字节填充。 (想想使用1 BPP一个1个像素宽位图,跨距为4,天真的公式会说,填充是4,但在现实中却是3),所以我们加一点点地覆盖<$ C $的情况下C>宽* BPP 不是一个字节边界,然后我们得到上面给出正确的公式。
But width * bpp
might not align on a byte boundary and when it doesn't this formula would over count the padding by a byte. (Think of a 1 pixel wide bitmap using 1 bpp. The stride is 4 and the naive formula would say that the padding is 4 but in reality it is 3.) So we add a little bit to cover the case that width * bpp
is not a byte boundary and then we get the correct formula given above.
这篇关于为什么BitmapSource.Create引发ArgumentException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!