Search code examples
copenglpngtextures

Using PNG images in OpenGL textures


I'm using OpenGL 1.4 and I would like to use a PNG image in an OpenGL texture. This is the code I used to initialize the texture (using SDL 1.2 and SDL image):

GLuint texture;
SDL_Surface *surface;
surface = IMG_Load("image.png");
glGenTextures(1,&texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,surface->w, surface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
SDL_FreeSurface(surface);

image.png is a 128x128 sized PNG image located in the same folder as the executable. Here is a screenshot of what I get:

problem

To compare, here is the original image:

originalimage

I tried exactly the same code with a bitmap image and it worked just fine.

Why does it do this? What is the correct way of doing?


Solution

  • Here is the problem.

    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,surface->w,surface->h,0,GL_RGB,GL_UNSIGNED_BYTE,surface->pixels);
    

    Your format parameter is incorrect. It should be:

    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,surface->w,surface->h,0,GL_RGBA,GL_UNSIGNED_BYTE,surface->pixels);
    

    GL_RGBA (not GL_RGB will represent 8 bits per channel which is what I think you need in your solution.)

    Please refer to https://www.opengl.org/sdk/docs/man/html/glTexImage2D.xhtml for more information.