Search code examples
cimageopenglsoil

Displayed image is corrupt on window /openGL


I'm trying to write a function which displays image. Function displays image but image is faint, inclined, uncolored and coating all of the screen. I used SOIL to load image.

GLuint texture_id=loadIm(file_name);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_id);
glLoadIdentity();
glColor3f(1, 1, 1);
glFrontFace(GL_CCW);
glCullFace(GL_FRONT);
glBindTexture(GL_TEXTURE_2D, texture_id);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glBegin(GL_QUADS);
glTexCoord2f(0,0); glVertex2f(0,    0.0);
glTexCoord2f(1,0); glVertex2f(ww, 0.0);
glTexCoord2f(1,1); glVertex2f(ww,wh);
glTexCoord2f(0,1); glVertex2f(0,  wh);
glEnd();
glFlush();
glutSwapBuffers();

If you want to check out loadIm function:

glEnable(GL_TEXTURE_2D);

    GLuint texture_id;
    glGenTextures(1, &texture_id);
width,height;

    glBindTexture(GL_TEXTURE_2D, texture_id);

    unsigned char *image = SOIL_load_image(file_name, &width, &height, 0, SOIL_LOAD_RGBA);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);


    printf("Width: %d \n Height: %d\n",width,height);
    printf("Texture ID: %d\n",texture_id);
    printf("Data: %p",image);

    SOIL_free_image_data(image);

    if (texture_id == -1) {
        return -1;
    }

    return texture_id;

Can I fix it? If yes, how can I?

EDIT: I found a way to fix faint and colorless problem. I just missed to change GL_RGB to GL_RGBA in loadIm function. But inclining and duplicating problems are continue.


Solution

  • Sounds like an alignment issue. Make sure the row alignment of what SOIL gives you matches with the pixel store unpack setting you're using with OpenGL to load the texture. IIRC SOIL always emits byte aligned images. So I suggest you add

    glPixelStore(GL_UNPACK_ALIGNMENT, 1);
    

    right before the call of glTexImage2D.