[英]Convert byte array to image in OpenGL ES 2.0
glViewport ( 0, 0, 320, 480 );
byte* memory
glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 1 );
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, memory);
我想將使用glreadpixel()
從幀緩沖區讀取的字節數組轉換為PNG / JPEG的任何圖像:
printf
語句顯示glreadpixel()
正在正確讀取內存。
我可以通過哪種方式將圖像寫入文件,例如:“ C:\\ image.jpg”?
OpenGL(包括ES)僅接受RAW紋理數據(即RGB三元組,RGBA四元組或某些其他預定義格式)或某些具有s3tc(S3紋理壓縮)的數據,但不接受文件格式。 與輸出相同。
編輯:
為確保元素實際出現在幀緩沖區中,必須在glReadPixels()調用之前立即完成glFlush()調用。 它將強制更新緩沖區。
加成:
如果您只需要將緩沖區內容轉儲到文件中,建議您使用.bmp文件格式。 它的開頭只是一個54字節的標頭,然后直接從OpenGL中讀取數據(不過請注意GL_UNPACK_ALIGNMENT)。
這是一個WriteBMP()函數供您使用:
void WriteBMP(const char *fname, int w,int h,unsigned char *img)
{
FILE *f = fopen(fname,"wb");
unsigned char bfh[54] = {0x42, 0x4d,
/* bfSize [2]*/ 54, 0, 0, 0, /**/
/* reserved [6]*/ 0, 0, 0, 0, /**/
/* biOffBits [10]*/ 54, 0, 0, 0, /**/
/* biSize [14]*/ 40, 0, 0, 0, /**/
/* width [18]*/ 0, 0, 0, 0, /**/
/* height [22]*/ 0, 0, 0, 0, /**/
/* planes [26]*/ 1, 0, /**/
/* bitcount [28]*/ 24, 0,/**/
/* compression [30]*/ 0, 0, 0, 0, /**/
/* size image [34]*/ 0, 0, 0, 0, /**/
/* xpermeter [38]*/ 0, 0, 0, 0, /**/
/* ypermeter [42]*/ 0, 0, 0, 0, /**/
/* clrused [46]*/ 0, 0, 0, 0, /**/
/* clrimportant [50]*/ 0, 0, 0, 0 /**/};
int realw = w * 3, rem = w % 4, isz = (realw + rem) * h, fsz = isz + 54;
//bfh.bfSize = fsz;
bfh[2] = (fsz & 0xFF); bfh[3] = (fsz >> 8) & 0xFF; bfh[4] = (fsz >> 16) & 0xFF; bfh[5] = (fsz >> 24) & 0xFF;
//bfh.biSize = isz
bfh[34] = (isz & 0xFF); bfh[35] = (isz >> 8) & 0xFF; bfh[36] = (isz >> 16) & 0xFF; bfh[37] = (isz >> 24) & 0xFF;
//bfh.biWidth = w;
bfh[18] = (w & 0xFF); bfh[19] = (w >> 8) & 0xFF; bfh[20] = (w >> 16) & 0xFF; bfh[21] = (w >> 24) & 0xFF;
//bfh.biHeight = h;
bfh[22] = (h & 0xFF); bfh[23] = (h >> 8) & 0xFF; bfh[24] = (h >> 16) & 0xFF; bfh[25] = (h >> 24) & 0xFF;
// xpels/ypels
// bfh[38] = 19; bfh[39] = 11;
// bfh[42] = 19; bfh[43] = 11;
fwrite((void*)bfh, 54, 1, f);
unsigned char* bstr = new unsigned char[realw], *remstr = 0;
if(rem != 0) { remstr = new unsigned char[rem]; memset(remstr,0,rem); }
for(int j = h-1 ; j > -1 ; j--){
for(int i = 0 ; i < w ; i++)
for(int k = 0 ; k < 3 ; k++) { bstr[i*3+k] = img[(j*realw+i*3)+(2-k)]; }
fwrite(bstr,realw,1,f); if (rem != 0) { fwrite(remstr,rem,1,f); }
}
delete [] bstr; if(remstr) delete [] remstr;
fclose(f);
}
然后只需撥打電話:
WriteBMP("C:\\image.bmp", 320, 480, memory);
如果確實需要.jpg / .png文件,則可以轉換生成的.bmp文件,或者使用FreeImage庫或libjpng / libpng本身。 它們都處理特定的文件格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.