Wednesday, April 27, 2005

BMP File Format

Hello!

I recently had occasion to do some programming with the bitmap file format. The bitmap (bmp) file format was originally created for Microsoft Windows version 1.0. It has evolved to version 5 and now includes compression and other nicities. In my dealings, I did not need these advanced features. What I found is that version 3 of the protocol suit me just fine!

While it should have been easy to accomplish my simple BMP manipulations, it was not. Some suggested that I switch programming languages and use prewritten libraries (some even posted suitable code in the comments at this blog). In the end, I decided to fight through it and see what I could learn. Most of what I learned can be found here:
http://astronomy.swin.edu.au/~pbourke/dataformats/bmp/
This site is very informative and very simple. While I did not use it, the source code linked from that site may be a useful reference for some programmers.

One important detail of the protocol that is not properly explained in that site is the required data alignment scheme. According to the protocol, the number of bytes representing each row in the image must be divisible by four. For example, consider a row of five pixels. Each pixel can be represented by a different number of bytes, but assume that each pixel takes 3 bytes. Therefore, in this example, each row requires 15 bytes. So, to conform to the protocol, a 1 byte padding must be applied before moving to the next row. This is very important.

Also, it is important to note that most C compilers will pad the bmp header data structure that is given in the aforementioned site. This means that you cannot simply write the structure to the file and assume everything will work. Each field must be written invidually. Of course, this is architecture and compiler independent so your mileage may vary. Just be careful.

Finally, remember that the BMP will be rendered to the screen in the opposite way that it is written into the file. In other words, the first data written to the file will be all the way at the bottom of the image. Not a big problem, just something of which to be aware.

Hope this helps someone, somewhere.

See you at the Guad!

No comments: