Writing a Bitmap Image

In an effort to stay "pure," my initial raytracer foregos using any graphics API (OpenGL, Direct3D) in favor of writing output directly to an image file on the disk. Once the basic raytracing code is in place, I will implement output to an OpenGL texture to be mapped to a fullscreen quad for slightly more intuitive display.

Writing to a standard bitmap file is fairly straightforward. It is made easier by ignoring many of the options allowed by the specification, like Run Length Encoding (RLE4/8) and using indexed colors. All that is needed to write a bitmap is slightly more than 50 bytes worth of information about the file, and a stream of unsigned char data representing the Red, Green, and Blue channels of the image.

After writing the library, I needed a way to test to make sure images were written correctly. As I wrote this before even starting the raytracer, I ended up making a set of image test cases. Some tests renders are below, compressed with Gimp for viewing on the web.

I make no guarantees regarding this code, but feel free to partake! It writes 24-bit bitmaps only with no compression. Furthermore, since the specification requires 32-bit (4-byte) alignment for each row of image data, the library writes images with widths that are powers of four.

Code: BMPLib.h, BMPLib.cpp, BMPTest.cpp.

Blue to Red Vertical Gradient
Red to Blue Gradient

Black and White Checkerboard
Black and White Checkerboard

Sine-based Curve
Sinusoidal spiral curve

Combination of Techniques
Combination of Techniques