dev_nut
dev_nut

Reputation: 2542

Using QImage to create a texture for OpenGL 4.5

This question seems to be asking the exact question, but it is asked in 2011 uses QGLWidget which is an outdated method, with the fixed pipeline.

I'm getting incorrect results when using QImage like this, where the texture image looks corrupted. Obviously, something is off and the bits are not returned in the expected RGB format. How do I use QImage correctly in this use case?

QImage img(texture.file_path.c_str());
unsigned char* actual_texture_img = img.bits();
int width = img.width();
int height = img.height();

if (!actual_texture_img) {
    return -1;
}

GLuint texture_id;
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);

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_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, actual_texture_img);

glGenerateMipmap(GL_TEXTURE_2D);

glBindTexture(GL_TEXTURE_2D, 0);

sample image with incorrect texture:

Incorrect texture loading

Upvotes: 1

Views: 1536

Answers (1)

dev_nut
dev_nut

Reputation: 2542

I have identified the fix for this. Interestingly, QImage in QT 5.11 (maybe in other versions too), defaults to loading images in the 32-bit ARGB format. So, I'm expecting the RGB 24-bit format or RGB_888, as input to glTexImage2D. The simple fix is to convert the image using the QImage function convertToFormat like so:

    img = img.convertToFormat(QImage::Format_RGB888);

It was a case of my openGL format, GL_RGB not matching the loaded format.

Upvotes: 1

Related Questions