Callum Linington
Callum Linington

Reputation: 14417

C# Image Class to Byte Array Length Issues

I use the Image class of C# to read in a file:

var image = Image.FromFile(filePath);

this now means image has been filled with Image data.

I now convert this image to a byte array:

static byte[] ImageToByteArray(Image imageIn)
{
    var ms = new MemoryStream();
    imageIn.Save(ms, ImageFormat.Bmp);
    return ms.ToArray();
}

Now I want to convert this Byte array to a matrix array, 2d byte array:

var imageMatrix = byte[image.Height, image.Width];

When I do a for loop moving values into the new byte matrix I get a IndexOutOfRangeException

On inspection,

var isImageLengthSameAsByteLength = imageByteArray.Length == (image.Width * image.Height);

isImageLengthSameAsByteLength value is false, after looking at the values, the array length is 132442 and (width * height) is 130995.

So there is clearly some disparity between these. I think that there is something extra that has been encoded into the image byte array, because obviously the height and width tells you the size of the image.

Any ideas, thanks,

Upvotes: 0

Views: 1592

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

You seem to be assuming that

imageIn.Save(ms, ImageFormat.Bmp);

will be writing exactly one byte per pixel. In fact, it's storing it in BMP format - which may well be more than one byte per pixel due to headers, and the fact that you can have more than 256 colours in a BMP file. Or it could be less than one byte per pixel if it's compressing the image.

Fundamentally, this transformation to a byte array isn't the one you want - so you'll need to work out an alternative approach. You might want to look at Bitmap.LockBits if it's actually a Bitmap object.

Upvotes: 3

Related Questions