سؤال

I've loaded a PNG image into my scene. While the image itself loads correctly (what I want to be displayed), the problem I'm having is with the transparency around the image. Where there should be transparency, there is white and black blobs filling that space.

void Renderer::loadTexture()
{
    const char textName[64] = ".\\foo.png";

    FIBITMAP *dib = FreeImage_Load(FIF_PNG, textName, PNG_DEFAULT);
    dib = FreeImage_ConvertTo24Bits(dib);


    if (FreeImage_GetBPP(dib) != 32) 
    {
        FIBITMAP* tempImage = dib;
        dib = FreeImage_ConvertTo32Bits(tempImage);
    }

    if (dib != NULL)
    {
        glGenTextures(1, &g_textureID);
        glBindTexture(GL_TEXTURE_2D, g_textureID);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        BYTE *bits = new BYTE[FreeImage_GetWidth(dib) * FreeImage_GetHeight(dib) * 4];

        BYTE *pixels = (BYTE*) FreeImage_GetBits(dib);

        for (int pix = 0; pix<FreeImage_GetWidth(dib) * FreeImage_GetHeight(dib); pix++)
        {
            bits[pix * 4 + 0] = pixels[pix * 4 + 2];
            bits[pix * 4 + 1] = pixels[pix * 4 + 1];
            bits[pix * 4 + 2] = pixels[pix * 4 + 0];
        }

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, FreeImage_GetWidth(dib), FreeImage_GetHeight(dib), 0,
        GL_RGBA, GL_UNSIGNED_BYTE, bits);

        cout << textName << " loaded." << endl;

        FreeImage_Unload(dib);
        delete bits;
    }


}
هل كانت مفيدة؟

المحلول

First, the GL_RGBA have one byte for each of Red, Green, Blue and Alpha (Alpha=transparency). Your code apparently didn't deal with alpha (the 4th byte of a pixel). Try to add the following line:

    for (int pix = 0; pix<FreeImage_GetWidth(dib) * FreeImage_GetHeight(dib); pix++)
    {
        bits[pix * 4 + 0] = pixels[pix * 4 + 2];
        bits[pix * 4 + 1] = pixels[pix * 4 + 1];
        bits[pix * 4 + 2] = pixels[pix * 4 + 0];
        bits[pix * 4 + 3] = pixels[pix * 4 + 3]; // Add this line to copy Alpha
    }

Second, if it still doesn't work, try to remove the FreeImage_ConvertTo24Bits line (even if it works please also try to remove this):

// dib = FreeImage_ConvertTo24Bits(dib); // Remove this line
if (FreeImage_GetBPP(dib) != 32) 
{
    FIBITMAP* tempImage = dib;
    dib = FreeImage_ConvertTo32Bits(tempImage);
}

It's strange to convert the image to 24 bits then back to 32 bits. Maybe it will discard the alpha channel.

I didn't tried to run the whole program and debug it. Just providing some hints that you can try.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top