I have a 2208 x 3000 TransformedBitmap object with format {Indexed8} that I'm do .CopyPixels() on. I'm using
(int)((formattedBitmap.PixelWidth * formattedBitmap.Format.BitsPerPixel + 7) / 8)
(assuming 'formattedBitmap' is the name of the image from which I'm trying to copy the pixels) for the 'stride' value in my method call and an array of bytes which is 2208 in length. I have something just like this working elsewhere in the code (where the format of the image is {Gray8}. However, where I'm trying to do this same thing on the aforementioned image, I continually get an "Argument Out of Range" exception saying "The parameter value cannot be less than '6624000'.\r\nParameter name: buffer."
My questions about this are: why in the world does the exact same code seem to work in one place and not the other? What in the world, in layman's terms, really IS the 'stride'? And how can I get the desired affect (of copying the bits) without getting this error? What am I doing wrong?
Any help to this would be very much appreciated. Thanks a lot!
I've figured this out (wow...kinda can't believe I spent something nigh an hour messing with this!). The problem was that the byte array has to be of size
sourceImage.PixelHeight * stride
where
int stride = (int)((sourceImage.PixelWidth * sourceImage.Format.BitsPerPixel + 7) / 8);
The reason that it worked in the other location in my code is because rather than copying the pixels for the entire image (as I'm trying to do where I was having the issue), I was only copying the pixels of a single row...that is, basically a 2008 x 1 area, so that the size of the destination byte array could be exactly 2208 and it would work fine. For future reference, something like this should probably always, more or less, be used:
int width = source.PixelWidth;
int height = source.PixelHeight;
int stride = width * ((source.Format.BitsPerPixel + 7) / 8);
byte[] bits = new byte[height * stride];
source.CopyPixels(bits, stride, 0);
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With