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;
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?
bpp = 32
so yes the formula reduces toRenderWidth * 4
. But there are odd cases (cheap LCDs use 18 bpp) and the fact that scanlines have to be aligned on 32-bit boundaries. I provided the general formula and an explanation of how to come up with it above. Hope it's elucidating. – Jason Dec 31 '09 at 5:090
becomes1
and1
becomes0
). I said that we want to ignore the lowest five bits ofwidth * bpp + 31
(and implicitly keep the rest). An easy way to do that is to make a number that has0
in those five bits and a1
in the rest of the bits; this is called a bitmask. If we take the logical andwidth * bpp + 31
with this bitmask (~31
) we have masked away the five low-order bits that we don't care about. Let me know if that isn't clear. – Jason Dec 31 '09 at 5:28((width * 24 + 23) & ~23) / 8;
works withPixelFormats.Rgb24;
. – PiZzL3 Jan 10 '12 at 3:52