[OpenGL] 获取画布背景的位图数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/felicityWSH/article/details/68946976

用OpenGL绘制好画面后 可以将画面数据保存成位图

本文给出一个获取位图数据的函数:

// get data of canvas rendered with OpenGL
// note : need to call delete[] for *pData
bool CaptureOpenGL(int& nWidth, int& nHeight, int& nPitch, BYTE** pData)
{
	static GLenum s_Format = GL_BGRA_EXT;
	static int s_nBytePerPixel = 4; // 4Byte : because pixel format is GL_BGRA_EXT

	nWidth = nHeight = nPitch = 0;
	*pData = NULL;

	GLint aViewport[4];
	glGetIntegerv(GL_VIEWPORT, aViewport);

	int width = aViewport[2];
	int height = aViewport[3];			 
	if ((width * height) <= 0)
		return false;
				
	int pitch = width * s_nBytePerPixel;
	int len = pitch * height;			 
	BYTE* pBuffer = new BYTE[len];
	if (!pBuffer)
		return false;
				 
	glPixelStorei(GL_PACK_ALIGNMENT, 1);
	glPixelStorei(GL_PACK_ROW_LENGTH, 0);
	glPixelStorei(GL_PACK_SKIP_ROWS, 0);
	glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

	GLenum lastBuffer;
	glGetIntegerv(GL_READ_BUFFER, (GLint*)&lastBuffer);
	glReadBuffer(GL_FRONT);
	glReadPixels(0, 0, width, height, s_Format, GL_UNSIGNED_BYTE, pBuffer);
	glReadBuffer(lastBuffer);
					 
	// reset value of alpha channel with 255. because sometimes the value is 0, such as CS1.6			 
	CWindowTool::ResetAlpha(pBuffer, len, 255); // this function should be completed by yourself

	nWidth = width;
	nHeight = height;
	nPitch = pitch;
	*pData = pBuffer;

	return true;
}


阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页