PPM files

From Hamsterworks Wiki!

Jump to: navigation, search

Portable Pixel Map (PPM) files are a nice easy way to access graphics files form your programs, and is well supported in Linux programs

The files do not support compression (this is either a feature of a limitation, depending on your use...), but have the benefits that the files are very easy to read and write.

PPM files come in many formats, support different colour depths but the most useful is the "P6" format as it allows you to create 24 bit colour images.

The header contains three lines of ASCII text, each terminated with a new line:

  • The file identifier of "P6"
  • The horizontal and vertical resolution, e.g. "800 600"
  • The maximum value of a pixel. e.g. "255".

This is followed with the raw pixel data, three bytes per pixel in Red Green Blue order.

Here's a C program to write an 800x600 image called "out.ppm":

#include <stdio.h>

#define WIDTH  800
#define HEIGHT 600

int main(int argc, char *argv[])
{
  int x,y;
  FILE *f = fopen("out.ppm","w");

  if(f==NULL) {
    fprintf(stderr,"Unable to open out.ppm");
    return 3;
  }
  fprintf(f,"P6\n");
  fprintf(f,"%i %i\n",WIDTH,HEIGHT);
  fprintf(f,"255\n");

  for(x = 0; x < WIDTH; x++)
    for(y = 0; y < HEIGHT; y++)
    {
      putc(x,  f); /* Red   */
      putc(y,  f); /* Green */
      putc(x+y,f); /* Blue  */
    }
  fclose(f);
  return 0;
}

Personal tools