Next post: Bit Packing Preprocessor

Image Output in C

If I'm writing some low level code (say, in C), at times I will want a quick way to quickly output an image file, and sometimes I'm too lazy to bring in a graphics library that can write actual .png files.

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.

Here is an example:
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
  }
}
fclose(fout);


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

chars = array.array('c') #char
chars.append('S')
chars.append('2')
chars.append('4')
chars.tofile(fout)

WIDTH=512; HEIGHT=256
ints = array.array('l') #signed long
ints.append(WIDTH)
ints.append(HEIGHT)
ints.tofile(fout)

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

bytes.tofile(fout)
fout.close()
(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 similar to how in Linux, one can write a .ppm file, which is, literally, a brief header and list of rgb values. It's funny, the .ppm format can even accept pixel information in human-readable ascii digits!

Download:
Windows binary
Source LGPL license.

Simpletobmp uses the LGPL bmp_io library by John Burkardt.