使用FreeImage提供的库,实现函数如下demo链接:https://github.com/liujiapeng550/jp_opengl
bool SaveImage(const char* imgpath)
{
//创建一块内存
unsigned char* mpixels = new unsigned char[800 * 600 * 4];
//glReadBuffer函数指明要从哪个颜色缓存中读取数据
glReadBuffer(GL_FRONT);
//glReadPixels 做了实际的读取工作
glReadPixels(0, 0, 800, 600, GL_BGRA, GL_UNSIGNED_BYTE, mpixels);
glReadBuffer(GL_NONE);
//for (int i = 0; i < (int)800 * 600 * 4; i += 4)
//{
// mpixels[i] ^= mpixels[i + 2] ^= mpixels[i] ^= mpixels[i + 2];
//}
FIBITMAP* bitmap = FreeImage_Allocate(800, 600, 32, 8, 8, 8);
for (int y = 0; y < FreeImage_GetHeight(bitmap); y++)
{
//bits返回指向位图数据位中给定扫描行开头的指针
BYTE* bits = FreeImage_GetScanLine(bitmap, y);
for (int x = 0; x < FreeImage_GetWidth(bitmap); x++)
{
bits[0] = mpixels[(y * 800 + x) * 4 + 0];
bits[1] = mpixels[(y * 800 + x) * 4 + 1];
bits[2] = mpixels[(y * 800 + x) * 4 + 2];
bits[3] = 255;
bits += 4;
}
}
//将先前加载的FIBITMAP保存到文件中
bool bSuccess = FreeImage_Save(FIF_PNG, bitmap, imgpath, PNG_DEFAULT);
//释放位图
FreeImage_Unload(bitmap);
return bSuccess;
}
本文由博客一文多发平台 OpenWrite 发布!