PDA

View Full Version : Saving PPMs...



Jeronimo
12-12-2001, 03:01 AM
Hi,

I've built a routine that saves snapshots of the scene in raw PPM format(see below). Everything works fine at first, but if I try to reshape the screen and then save the image I get apparently random results : crashes (page fault), saves badly and sometimes it works out fine. If I increase the size of the allocated memory to 'snap_image', it doesn't crash but the resulting image is wrong. I think the problem is with the glReadPixels() routine, because when I comment it and save an image with rgb values generated by me, it works fine independently of the current window dimensions.

//////////////FUNCTION/////////////////////

width1 and height1 are the current window
dimensions generated by the reshape callback(they are correct)

void take_snapshot(void)
{
FILE *fp;
unsigned char *snap_image;
int i, j;

/* Allocate memory for image */
snap_image = (unsigned char *)malloc(sizeof(unsigned char)*(width1)*(height1)*3);

/* Read the image from the color buffer */
glReadPixels(0,0,width1,height1,GL_RGB, GL_UNSIGNED_BYTE, snap_image);

/* Open destination file. Needs to be in binary mode */
if( (fp = fopen("snapshot.ppm","wb")) == NULL)
{
puts("Sorry, file could not be saved");
exit(EXIT_FAILURE);
}

/* Write PPM header */
fprintf(fp,"P6 %d %d 255 ",width1,height1);

/* Save image */
for(i=(width1)*(height1)*3-(width1)*3;i>=0;i-=(width1)*3)
for(j=i;j<i+(width1)*3;j++)
fwrite(&snap_image[j],sizeof(unsigned char), 1, fp);

/* Close file */
fclose(fp);
}

Can someone help me out? Thanks in advance.

Frederico Jeronimo