Saving screen to bitmap

Hi, I need to save the screen to a bitmap,
Ive found the bitmap format out, but my program just doesnt work, does anyone know of any source code (in OpenGL) which does this?


Use glReadPixels to grab the bits from the screen.


I use glreadpixels

I am using a 24 bit format, and I think it is to do with the way I am formatting my data (currently I am simply packing 3bytes (RGB) one after the other, is this right?

(I use the two MS structures beforehand)

I’m very familiar with the frustations of getting bitmaps to write to disk correctly.

I’m sorry that this code is not going to work for you right out of the box because I use a custom file class that is similar to CArchive, but hopefully it will help. Pay special attention to how each line in the bitmap has to be dword aligned at the fact that you can’t just right a memory structure (BITMAPFILEHEADER) directly to disk because it is dword aligned in memory.

void SaveBitmap(int width, int height, unsigned char* pRGB)
int dwWidth=(width24+31)/324; // get dword aligned width
int i,j;

// open file

bmfHeader.bfType=((unsigned short) ('M' << 8) | 'B');

//Need to write out each field separately because of memory alignment issues
//file.Write((char *)&bmfHeader, 14);
file << bmfHeader.bfType; 
file << bmfHeader.bfSize;     
file << bmfHeader.bfReserved1;     
file << bmfHeader.bfReserved2; 
file << bmfHeader.bfOffBits; 



for (i=0;i<height;i++)
	for (j=0;j<width;j++)
		file << pRGB[i*width*3+j*3+2];
		file << pRGB[i*width*3+j*3+1];
		file << pRGB[i*width*3+j*3];
	for (j=width*3;j<dwWidth;j++)
		file << (unsigned char)0;


Dunno, does it have to be a .bmp format? I wrote a simple tga routine and it works fine…if nothing else, you could probably model a .bmp screenshot function after it though…good luck.

int t = 18 + * * 3;
unsigned char *buffer=(unsigned char *)malloc(t);
unsigned char temp;

// create the header

buffer[2] = 2;// uncompressed
buffer[12] = & 255;
buffer[13] = >> 8;
buffer[14] = & 255;
buffer[15] = >> 8;
buffer[16] = 24; // bit depth

glReadPixels( 0, 0,,, GL_RGB, GL_UNSIGNED_BYTE, buffer + 18 );

// swap rgb to bgr
for ( i = 18; i < t; i += 3 )
temp = buffer[i];
buffer[i] = buffer[i + 2];
buffer[i + 2] = temp;

// write buffer out here…

[This message has been edited by El Jefe (edited 09-28-2000).]

Ive done it at last! Thanks for the replies they certainly helped me find out my problem. I had some dodgy code when I was reading in the pixels, but looking at yours, I realised that I could read them all in at once (much faster as well)


Originally posted by David:
Hi, I need to save the screen to a bitmap,

Look here:

and see my post… three functions that
write the framebuffer in PPM, TGA or
BMP format

Hope this helps