[offtopic] Re: [ODE] writing to ppm file

Tim Field nobbis at mcs.vuw.ac.nz
Tue Aug 19 14:52:02 2003


On Wed, 2003-08-20 at 02:23, Adam D. Moss wrote:
> Koby Zalmanson wrote:
> > Our goal is to capture an image of the frame, we succeeded to read with 
> > the function glReadPixel the frame into an array of chars;
> > 
> > It is defined in our code: char pixels[WIDTH*HEIGHT*3] ;
> > 
> > Now we want to create a ppm file, but we do not know how to write the 
> > data to file in the way it should be written to a ppm file.
> > 
> > Is anyone has a source or some example of how to write this data to a 
> > file correctly?
> 
> The format is completely trivial.  For a 24-bit 8-bit-per-channel
> unsigned char RGB image you can write:
> 
> P6\n(WIDTH) (HEIGHT)\n255\n(raw pixel data dump: r,g,b from
> top-left to bottom-right)
> 
> So, say, this would be a valid PPM file:
> 
> P6
> 3 3
> 255
> kn94hdl4hkr8dheyr9dncb4ydtf

Just in case you wanted the answer handed to you on a plate:

  // Open file.
  ofstream os("capture.ppm", ios::out | ios::trunc);

  // Write header.
  static char buffer[256];
  sprintf(buffer, "P6 %u %u 255\n", WIDTH, HEIGHT);
  os.write(buffer, strlen(buffer));

  // Write data.
  for (GLuint y = HEIGHT - 1; y < HEIGHT; --y)
      os.write((char*)pixels + y * WIDTH * 3, WIDTH * 3);
  
  // Close file.
  os.close();

As an aside, there's probably an argument for such function to 
be included in drawstuff, no?


tim.