用 glReadPixels(..) 可以读出CView窗里画的东西的像素,有了每一点的RGB值就可以写图像文件.写bmp文件比较简单些.写jpg,gif等复杂些.写jpg最好用JPEG工作组的JPEG库(免费的).
这里有把CView窗图像RGB值送到clipboard的码,随便用什么图像编辑软件粘贴存放成你想要的图像格式.
// Snap OpenGL client and send it to ClipBoard
// so that you can insert it in your favorite
// image editor, Powerpoint, etc...
// Replace CRenderView by your own CView-derived class
void CRenderView::SnapClient()
{
BeginWaitCursor();
// Get client geometry
CRect rect;
GetClientRect(&rect);
CSize size(rect.Width(),rect.Height());
TRACE(" client zone : (%d;%d)\
",size.cx,size.cy);
// Lines have to be 32 bytes aligned, suppose 24 bits per pixel
// I just cropped it
size.cx -= size.cx % 4;
TRACE(" final client zone : (%d;%d)\
",size.cx,size.cy);
// Create a bitmap and select it in the device context
// Note that this will never be used ;-) but no matter
CBitmap bitmap;
CDC *pDC = GetDC();
CDC MemDC;
ASSERT(MemDC.CreateCompatibleDC(NULL));
ASSERT(bitmap.CreateCompatibleBitmap(pDC,size.cx,size.cy));
MemDC.SelectObject(&bitmap);
// Alloc pixel bytes
int NbBytes = 3 * size.cx * size.cy;
unsigned char *pPixelData = new unsigned char[NbBytes];
// Copy from OpenGL
::glReadPixels(0,0,size.cx,size.cy,GL_RGB,GL_UNSIGNED_BYTE,pPixelData);
// Fill header
BITMAPINFOHEADER header;
header.biWidth = size.cx;
header.biHeight = size.cy;
header.biSizeImage = NbBytes;
header.biSize = 40;
header.biPlanes = 1;
header.biBitCount = 3 * 8; // RGB
header.biCompression = 0;
header.biXPelsPerMeter = 0;
header.biYPelsPerMeter = 0;
header.biClrUsed = 0;
header.biClrImportant = 0;
// Generate handle
HANDLE handle = (HANDLE)::GlobalAlloc (GHND,sizeof(BITMAPINFOHEADER) + NbBytes);
if(handle != NULL)
{
// Lock handle
char *pData = (char *) ::GlobalLock((HGLOBAL)handle);
// Copy header and data
memcpy(pData,&header,sizeof(BITMAPINFOHEADER));
memcpy(pData+sizeof(BITMAPINFOHEADER),pPixelData,NbBytes);
// Unlock
::GlobalUnlock((HGLOBAL)handle);
// Push DIB in clipboard
OpenClipboard();
EmptyClipboard();
SetClipboardData(CF_DIB,handle);
CloseClipboard();
}
// Cleanup
MemDC.DeleteDC();
bitmap.DeleteObject();
delete [] pPixelData;
EndWaitCursor();
}