Question

Trying to get the valid size of BMP file.

Of course the best way is just to get the Length property of the loaded stream.

But BMP header format DOES include the information about its size and I want to try to get it exactly from BMP header.

As from Wiki or other source:

http://en.wikipedia.org/wiki/BMP_file_format

offset: 0002h | 4 bytes | the size of the BMP file in bytes 

So the size value is included in BMP header in region of 4 bytes ( from [2] -> [5]: 2, 3, 4, 5 )

So first of all I thought to get all byte values and sum the all:

1).

int BMPGetFileSize(ref byte[] headerPart)
{
    int fileSize = 0;

    for (int i = 0; i < headerPart.Length; i++)
    {
        fileSize += headerPart[i];
    }

    return (fileSize > 0) ? fileSize : -1;
}

I've got a very small size... For my file, the actual size is 901:

enter image description here

But, I've got from the code: 84.

I've checked for the correct region, I thought that I can get not the correct values, BUT I've got it correctly ( from 2nd till 5th from byte[] data of BMP ).

2). Then I thought, that I must not sum them, but just to write at one string line all the values and then convert it to System.Int32 and divide on 1024 to get the size in Kbytes, but again... it doesn't equal to the 901 Kb value.

enter image description here

You may thought, that I've confused the region and selecting wrong values, when you look at watch dialog and compare it with the function code, but as you see the byte[] array from function is: headerPart, not data, so I didn't confuse anything, data[] is the file stream of whole BMP file.

So, how could I get file size from BMP header, not from the property of stream in C#?

Was it helpful?

Solution

The BMP file format is a binary format, which means you cannot read it using a StreamReader or TextReader (which are both used only for text) or decode it with a UTF-8 or ANSI decoder. (Encodings are also used only for text.) You have to read it using a BinaryReader.

The documentation states:

offset: 0002h | 4 bytes | the size of the BMP file in bytes

So you need to read four bytes and combine them into an integer value.

With the BinaryReader class you can call the ReadUInt32() method to read 4 bytes that form an unsigned 32-bit integer.

If you do that, you'll see it reads:

921654

...which is 900 KiB and then some.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top