OpenGL Texture Example

The loadtexture function below loads an image into a SDL_Surface using SDL_image then getting it into OpenGL. It accepts a filename path and returns an OpenGL "Texture Name" which is a handle to the texture. The function only supports 24 bit and 32 bit coloured images.

The drawtexture function below draws a Image at (x,y) as a textureid.

OpenGL textures must obey certain dimensions. In this example,they must be a power of two. eg: 512x128, 2x1024, 128x128, etc, if not, you should use 'gluBuild2DMipmaps'.

void EnableTransparency()

GLuint LoadTexture(char *filename,int *textw,int *texth) {

        SDL_Surface *surface;
        GLuint textureid;
        int mode;

        surface = IMG_Load(filename);

        // Or if you don't use SDL_image you can use SDL_LoadBMP here instead:
        // surface = SDL_LoadBMP(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;

        } else if (surface->format->BytesPerPixel == 4) { // RGBA 32bit

                mode = GL_RGBA;

        } else {

                return 0;


        // 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...

        // clean up

        return textureid;


void DrawTexture(int x, int y, GLuint textureid,int textw,int texth) {

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

        // make a rectangle

        // top left
        glTexCoord2i(0, 0);
        glVertex3f(x, y, 0);

        // top right
        glTexCoord2i(1, 0);
        glVertex3f(x+textw, y, 0);

        // bottom right
        glTexCoord2i(1, 1);
        glVertex3f(x+textw, y+texth, 0);

        // bottom left
        glTexCoord2i(0, 1);
        glVertex3f(x, y+texth, 0);

        glDisable(GL_TEXTURE_2D );

int main(int argc,char **argv)

  GLuint myglu;
  int textw,texth;



OpenGL_Texture_Example (last edited 2008-08-11 19:06:47 by Stefan Buss)