OpenGL-保存BMP圖片


bool screenshot(const char* filename)
{
GLenum lastBuffer;
GLbyte* pBits = 0; // 圖像數據
unsigned long lImageSize;
GLint iViewport[4]; // 視圖大小

glGetIntegerv(GL_VIEWPORT, iViewport);
lImageSize = iViewport[2] * iViewport[3] * 3;

pBits = (GLbyte*)new unsigned char[lImageSize];
if (!pBits)
return false;

// 從color buffer中讀取數據
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

//
glGetIntegerv(GL_READ_BUFFER, (GLint*)&lastBuffer);
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, iViewport[2], iViewport[3], GL_BGR_EXT, GL_UNSIGNED_BYTE, pBits);
glReadBuffer(lastBuffer);

if (writeBMP(filename, (unsigned char*)pBits, iViewport[2], iViewport[3]))
return true;

return false;

}


bool writeBMP(const char filename[], unsigned char* data, unsigned int w, unsigned int h)
{
std::ofstream out_file;

/** 檢查data */
if(!data) 
{
std::cerr << "data corrupted! " << std::endl;
out_file.close();
return false;
}

/** 創建位圖文件信息和位圖文件頭結構 */
BITMAPFILEHEADER header;
BITMAPINFOHEADER bitmapInfoHeader;

//unsigned char textureColors = 0;/**< 用於將圖像顏色從BGR變換到RGB */

/** 打開文件,並檢查錯誤 */
out_file.open(filename, std::ios::out | std::ios::binary);
if (!out_file)
{
std::cerr << "Unable to open file " << filename << std::endl;
return false;
}

/** 填充BITMAPFILEHEADER */
header.bfType = BITMAP_ID;
header.bfSize = w*h*3 + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
header.bfReserved1 = 0;
header.bfReserved2 = 0;
header.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
/** 寫入位圖文件頭信息 */
out_file.write((char*)&header, sizeof(BITMAPFILEHEADER));

/** 填充BITMAPINFOHEADER */
bitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfoHeader.biWidth = w;
bitmapInfoHeader.biHeight = h;
bitmapInfoHeader.biPlanes = 1;
bitmapInfoHeader.biBitCount = 24;
bitmapInfoHeader.biCompression = BI_RGB; // BI_RLE4 BI_RLE8
bitmapInfoHeader.biSizeImage = w * h * 3; // 當壓縮類型為BI_RGB是也可以設置為0
bitmapInfoHeader.biXPelsPerMeter = 0;
bitmapInfoHeader.biYPelsPerMeter = 0;
bitmapInfoHeader.biClrUsed = 0;
bitmapInfoHeader.biClrImportant = 0;
/** 寫入位圖文件信息 */
out_file.write((char*)&bitmapInfoHeader, sizeof(BITMAPINFOHEADER));

/** 將指針移到數據開始位置 */
out_file.seekp(header.bfOffBits, std::ios::beg);

/** 寫入圖像數據 */
out_file.write((char*)data, bitmapInfoHeader.biSizeImage);

out_file.close();
return true;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM