My Code
void SetPixel(int x, int y)
{
unsigned char* offset = mImageData + (x + mImageHeight * y) * sizeof(unsigned char) * 3;
offset[0] = 255;
offset[1] = 0;
offset[2] = 0;
}
And
for (int j = imageHeight - 1; j >= 0; j--)
{
for (int i = 0; i < imageWidth; i++)
{
SetPixel(i, j);
}
}
OpengL code:
Create: m_InternalFormat = GL_RGB8; m_DataFormat = GL_RGB; m_Data = new unsigned char[width * height * 3];
glGenTextures(1, &m_RendererID);
glBindTexture(GL_TEXTURE_2D, m_RendererID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
Set Data:
glBindTexture(GL_TEXTURE_2D, m_RendererID);
if(alpha)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
else
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, m_Width, m_Height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
Now i should get a Red Texture but i am getting :
See The top left corner. The texture is wrong.
I think this might be due to not setting the correct pixel offset. But i cant figure out exactly what is wrong ? Please Help.
By default OpenGL assumes that the start of each row of an image is aligned to 4 bytes. This is because the GL_UNPACK_ALIGNMENT
parameter by default is 4. Since the image has 3 color channels (GL_RGB
), and is tightly packed the size of a row of the image may not be aligned to 4 bytes.
When a RGB image with 3 color channels is loaded to a texture object and 3*width is not divisible by 4, GL_UNPACK_ALIGNMENT
has to be set to 1, before specifying the texture image with glTexImage2D
:
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, m_Width, m_Height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);