Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert QImage format to format supported by OpenGL

Tags:

c++

qt

opengl

qt4

I'm using QImage to load images which then used as textures in OpenGL. The problem is that color components have different order in QImage and OpenGL. Currently I'm using GL_RGBA format in OpenGL and QImage::Format_ARGB32 in Qt. Because of that, I have to manually swap bytes for each pixel of loaded image, before creating a texture in OpenGL. Moreover, to swap bytes correctly I need to know endianness of a machine.

Does anyone know a better solution for this? At least, is there any way to make this conversion endianness-independent?

Thanks.

like image 650
ovk Avatar asked Jul 16 '11 19:07

ovk


1 Answers

The last three parameters to glTex(Sub)Image define how the pixel transfer to OpenGL takes place. If you have 4 8-bit values, sequentially, in the ARGB order, then I would suggest the following:

glTexImage2D(..., GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, *);

To deal with endian conversion issues, use glPixelStore parameters. Specifically, GL_UNPACK_SWAP_BYTES. The above is designed for little-endian machines, so if you're on a big-endian machine you should call glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_TRUE); before calling this function, and then set it back to GL_FALSE afterwards.


Note: I know you didn't mention it, but in case you're considering mobile platforms, remember that OpenGL ES is not OpenGL. Desktop OpenGL requires implementations to be able to handle a wide variety of pixel arrangements in transfer operations. GL ES mandates almost the opposite. The pixel transfer formats must exactly match the internal format of the texture. So if you were doing GL ES development, you would have to do the byte swapping on your own.

like image 132
Nicol Bolas Avatar answered Sep 19 '22 22:09

Nicol Bolas