2016-04-27 97 views
1

當我嘗試使用SDL_image將圖像加載到OpenGL紋理時,我收到了意外的輸出。SDL OpenGL紋理困擾綠色色調

我的代碼的相關部分:

/** 
* Load texture 
* @param {char*} [filename] File name to load 
* @param {int*} [textw] Texture width pointer (value returned) 
* @param {int*} [texth] Texture height pointer (value returned) 
* @return {GLuint} 
* @link http://sdl.beuc.net/sdl.wiki/OpenGL_Texture_Example 
**/ 
GLuint LoadTexture(char *filename, int *textw, int *texth) { 

    GLuint textureid; 
    int mode; 

    SDL_Surface *surface = IMG_Load(filename); 

    // could not load filename 
    if (!surface) { 
     return 0; 
    } 

    // work out what format to tell glTexImage2D to use... 
    if (surface->format->BytesPerPixel == 3) { // RGB 24bit 
     mode = GL_RGB; 
     printf("GL_RGB\n"); 
    } else if (surface->format->BytesPerPixel == 4) { // RGBA 32bit 
     mode = GL_RGBA; 
     printf("GL_RGBA\n"); 
    } else { 
     SDL_FreeSurface(surface); 
     return 0; 
    } 

    // Record texture dimensions 
    *textw = surface->w; 
    *texth = surface->h; 

    // create one texture name 
    glGenTextures(1, &textureid); 

    // tell opengl to use the generated texture name 
    glBindTexture(GL_TEXTURE_2D, textureid); 

    // this reads from the sdl surface and puts it into an opengl texture 
    glTexImage2D(GL_TEXTURE_2D, 0, mode, surface->w, surface->h, 0, mode, GL_UNSIGNED_BYTE, surface->pixels); 

    // these affect how this texture is drawn later on... 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 

    // clean up 
    SDL_FreeSurface(surface); 

    return textureid; 

} 

/** 
* Render 
* @param {GLuint} [textureid] OpenGL texture to apply 
**/ 
void render(textureid) { 

    //Clear color buffer 
    glClear(GL_COLOR_BUFFER_BIT); 

    //Render quad 
    if (gRenderQuad) { 

     // Set color 
     glColor3f(0.0f,1.0f,0.0f); 

     // tell opengl to use the generated texture name 
     glBindTexture(GL_TEXTURE_2D, textureid); 
     glEnable(GL_TEXTURE_2D); 

     // Draw rectangle 
     glBegin(GL_QUADS); 

     // Top left 
     glTexCoord2i(0, 1); 
     glVertex2f(-1.0f, -1.0f); 

     // Top right 
     glTexCoord2i(1, 1); 
     glVertex2f(1.0f, -1.0f); 

     // Bottom left 
     glTexCoord2i(1, 0); 
     glVertex2f(1.0f, 1.0f); 

     // Bottom right 
     glTexCoord2i(0, 0); 
     glVertex2f(-1.0f, 1.0f); 

     glEnd(); 

     glDisable(GL_TEXTURE_2D); 

    } 

} 

本機圖像I負荷是:

input.jpg

但輸出是:

output.jpg

從我在anot上讀過的東西她的堆棧溢出post,我相信這可能是一個倒轉的渠道問題,但提出的解決方案不能解決我的問題。我的方法/代碼有什麼問題?

回答

2

據我所知,加載紋理沒有任何問題。輸出有一個綠色的色調的原因是因爲你設置:

glColor3f(0.0f, 1.0f, 0.0f); 

這個顏色值將與紋理意義的顏色樣本相乘最終輸出的紅色和藍色分量將始終爲0,這這就是爲什麼圖像看起來有綠色色調。如果你想使用原始的紋理顏色,你應該始終設置:

glColor3f(1.0f, 1.0f, 1.0f); 
+0

應用你的建議,哪個工作,然後我注意到,顏色被顛倒。我通過使用GL_BGRA作爲glTexImage2D()函數的格式參數來解決此問題。 –