Bill Sun
Bill Sun

Reputation: 51

Texture turns to gray in opengl when added alpha channel manually

int j,k,t3,t4;
for (int i = 0;i < width;i++)
    for (j = 0;j < height;j++)
    {
        t3 = (i*height + j)*3 ;
        t4 = (i*height + j) * 4;
        for (k = 0;k < 3;k++)
            texture[t4+k] = data[t3+k];
        texture[t4 + 3] = (data[t3 + 1]==255 && data[t3 + 2]==255 && data[t3]==255) ? 0 : 255;
    }


GLuint textureID;
glGenTextures(1, &textureID);

glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, texture);

It's a Bitmap file and I loaded it successfully with the original data.

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);

But when I added the Alpha channel manually the texture losts its color.The picture is attached below. After modification on texture data. Before Transparency is added.

Upvotes: 0

Views: 595

Answers (1)

Reto Koradi
Reto Koradi

Reputation: 54652

I can't quite explain the exact symptoms, but the index arithmetic in your code looks off:

for (int i = 0;i < width;i++)
    for (j = 0;j < height;j++)
    {
        t3 = (i*height + j)*3 ;
        t4 = (i*height + j) * 4;

Since images are normally laid out in memory row by row, the index that iterates over the pixels in the row should be the one added without a multiplier, while the other index is multiplied by width (not height). This should be:

for (j = 0; j < height; j++)
    for (int i = 0; i < width; i++)
    {
        t3 = (j * width + i) * 3;
        t4 = (j * width + i) * 4;

Upvotes: 1

Related Questions