Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 980
Donald Duck Avatar asked Jan 24 '26 17:01

Donald Duck


1 Answers

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.

like image 71
Harish Avatar answered Jan 26 '26 11:01

Harish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!