1

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;
    }


}
4

1 回答 1

2

首先,GL_RGBA 对 Red、Green、Blue 和 Alpha 各有一个字节(Alpha=transparency)。您的代码显然没有处理 alpha(像素的第 4 个字节)。尝试添加以下行:

    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
    }

其次,如果仍然不起作用,请尝试删除该FreeImage_ConvertTo24Bits行(即使它有效也请尝试删除此行):

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

将图像转换为 24 位然后再转换回 32 位很奇怪。也许它会丢弃 alpha 通道。

我没有尝试运行整个程序并对其进行调试。只是提供一些您可以尝试的提示。

于 2013-11-09T09:31:01.030 回答