Image Output in C

Sometimes, it can be nice to have a dead-simple format for bitmap images. If I'm writing some low level code (say, in C) dealing with graphics, at times I will want a quick way to quickly output an image file. Let's say that I'm too lazy to bring in a graphics library that can write actual .pngs . The .bmp format, while simple, is a bit more complicated than a list of rgb values, because of alignment.

I wrote a little program that converts ".simple" images (which are a list of R,G,B bytes) into 24 bit .bmp files. So, your program simply writes a tiny header and three bytes per pixel, and simpletobmp.exe turns this into a .bmp.

This works well from Python, too, when the PIL isn't around.

Here is an example of how to draw a ".simple" image:
FILE * fout;
fout = fopen("test.simple","wb");
fputc('S', fout);
fputc('2', fout);
fputc('4', fout);
int x,y,width,height;
width = 512; height = 256;
fwrite(&width,sizeof(int), 1, fout); 
fwrite(&height,sizeof(int), 1, fout); 

for (y=0; y<height; y++)
  for (x=0; x<width; x++)
    fputc( y%256 , fout); //Red
    fputc( x%256 , fout); //Green
    fputc( 0 , fout);          //Blue

Or, in Python,

import array
fout = open('pyout.simple', 'wb')

chars = array.array('c') #char

ints = array.array('l') #signed long

bytes = array.array('B') #unsigned char
for y in range(HEIGHT):
 for x in range(WIDTH):

(This one draws a gradient in red and green. Change the fputc lines in the inner loop to draw the image you want. A common usage is to set up a 2d array of pixels, draw the picture into that array, and then output everything to a file).

Now, one can run
simpletobmp.exe o test.simple test.bmp
to get the image.

This is very similar to how in Linux, one can write a .ppm file, which is, literally, a brief header and list of rgb values. The .ppm format even accepts pixel information in human-readable ascii digits! Sounds ridiculous, but this type of thing can be useful.

Windows binary
Source LGPL license.

Simpletobmp uses the LGPL bmp_io library by John Burkardt.