freeimage loading png with transparency c ++

时间:2013-11-09 09:15:19

标签: c++ opengl-3 freeimage

我已将PNG图像加载到场景中。虽然图像本身正确加载(我想要显示的内容),但我遇到的问题是图像周围的透明度。在应该有透明度的地方,有白色和黑色的斑点填充那个空间。

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


}

1 个答案:

答案 0 :(得分:3)

首先,GL_RGBA对红色,绿色,蓝色和Alpha(Alpha =透明度)各有一个字节。你的代码显然没有处理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通道。

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