簡體   English   中英

使用glReadPixels讀取紋理字節?

[英]Read texture bytes with glReadPixels?

我想將原始紋理數據轉儲到磁盤(以供以后讀取),而且我不確定glReadPixel是否會從當前綁定的紋理中讀取數據。

如何從紋理讀取緩沖區?

glReadPixels函數從幀緩沖區而不是紋理讀取。 要讀取紋理對象,您必須使用glGetTexImage,它在OpenGL ES中不可用 :(

如果要從紋理讀取緩沖區,則可以將其綁定到FBO(FrameBuffer對象)並使用glReadPixels

//Generate a new FBO. It will contain your texture.
glGenFramebuffersOES(1, &offscreen_framebuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, offscreen_framebuffer);

//Create the texture 
glGenTextures(1, &my_texture);
glBindTexture(GL_TEXTURE_2D, my_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,  width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

//Bind the texture to your FBO
glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, my_texture, 0);

//Test if everything failed    
GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
if(status != GL_FRAMEBUFFER_COMPLETE_OES) {
    printf("failed to make complete framebuffer object %x", status);
}

然后,僅當要從紋理讀取時,才必須調用glReadPixels:

//Bind the FBO
glBindFramebufferOES(GL_FRAMEBUFFER_OES, offscreen_framebuffer);
// set the viewport as the FBO won't be the same dimension as the screen
glViewport(0, 0, width, height);

GLubyte* pixels = (GLubyte*) malloc(width * height * sizeof(GLubyte) * 4);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

//Bind your main FBO again
glBindFramebufferOES(GL_FRAMEBUFFER_OES, screen_framebuffer);
// set the viewport as the FBO won't be the same dimension as the screen
glViewport(0, 0, screen_width, screen_height);

感謝您的回答Gergonzale。 我今天早上花了一些時間試圖弄清楚如何使其與16位紋理一起使用,此代碼段可能對將GL_UNSIGNED_SHORT_5_6_5轉換為GL_UNSIGNED_BYTE的其他任何人都有用

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,  tSizeW, tSizeH, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL);
GLubyte* pixels = (GLubyte*) malloc(tSizeW * tSizeH * sizeof(GLubyte) * 2);
glReadPixels(0, 0, tSizeW, tSizeH, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);

int index = (x*tSizeH + y)*2;
unsigned int rgb = pixels[index + 1]*256 + pixels[index + 0];
unsigned int r = rgb;
r &= 0xF800;    // 1111 1000 0000 0000
r >>= 11;       // 0001 1111
r *= (255/31.); // Convert from 31 max to 255 max

unsigned int g = rgb;
g &= 0x7E0;     // 0000 0111 1110 0000
g >>= 5;        // 0011 1111
g *= (255/63.); // Convert from 63 max to 255 max

unsigned int b = rgb;
b &= 0x1F;      // 0000 0000 0001 1111
//g >>= 0;      // 0001 1111
b *= (255/31.); // Convert from 31 max to 255 max

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM