tags:

views:

158

answers:

2

I have a non transparent, colour bitmap with length 2480 and width 3507.

Using Bitmap.GetPixel(int x, int y) I am able to get the colour information of each pixel in the bitmap.

If I squirt the bitmap into a byte[]:

MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Bmp);
ms.Position = 0;
byte[] bytes = ms.ToArray();

then I'd expect to have the same information, i.e. I can go to bytes[1000] and read the colour information for that pixel.

It turns out that my array of bytes is larger than I anticipated. I thought I'd get an array with 2480 x 3507 = 8697360 elements. Instead I get an array with 8698438 elements - some sort of header I presume.

In what format the bytes in my array stored? Is there a header 1078 bytes long followed by Alpha, Red, Green, Blue values for every byte element, or something else?

All I need is the colour information for each pixel. I'm not concerned with the header (or indeed the transparency) unless I need it to get the colour info.

+2  A: 

You're calling GetBuffer which returns the underlying byte array - that's bigger than the actual length of the stream.

Either use

byte[] bytes = ms.ToArray();

or use GetBuffer but in conjunction with ms.Length.

Having said that, you're saving it as a BMP - so there'll be header information as well; it's not like the first byte will represent the first pixel. Unfortunately there's no "raw" image format as far as I can see... that's what it sounds like you really want.

You could use Bitmap.LockBits and then copy the data from there, if you want...

Jon Skeet
I've changed my code to get the array but I'm still getting the same number of bytes (I guess I was lucky with my MemoryStream)
Matt Jacobsen
Thanks, Lockbits is what I need. I think http://www.bobpowell.net/lockingbits.htm will help get me where I need to go.
Matt Jacobsen
A: 

If I understand correctly the documentation about Bitmap.Save, it saves the image in the specified format, which means that you'll have in your bytes array, the bitmap header. I think you should read some documentation about the bitmap format to know how to get the needed information in your array

PierrOz
pray tell, what is the specified format?? Is it DB or DIB? What's in the header? Is it always a constant size or does it vary with the phase of the moon?
Matt Jacobsen