如何将索引的PNG图像用作SDL2 / OpenGL的纹理

时间:2015-01-28 02:59:47

标签: c++ opengl sdl sdl-2 libpng

我加载图片的代码似乎适用于24和32位图像。我使用SDL2_image加载图像:

// Snip cruft above
if((surface = IMG_Load(filename.c_str())) == NULL) {
    error = "Unable to load file: " + filename;
    throw error.c_str();
}


// get the number of channels in the SDL surface
nOfColors = surface->format->BytesPerPixel;

if (nOfColors == 4) {    // contains an alpha channel
    if (surface->format->Rmask == 0x000000ff)
        texture_format = GL_RGBA;
    else
        texture_format = GL_BGRA;
} else if (nOfColors == 3) {    // no alpha channel
    if (surface->format->Rmask == 0x000000ff)
        texture_format = GL_RGB;
    else
        texture_format = GL_BGR;
} else {
    error = "error: the image is not truecolor..  this will probably break (" + filename + " contains " + std::to_string(nOfColors) + " bytes per pixel)";
    throw error.c_str();
}
// snip OpenGL stuff below

nOfColors仅包含值1,因为PNG保存为索引颜色空间。 GIMP打开文件很好,包括alpha通道。

如何将曲面转换为真彩色纹理,以便在OpenGL四元组上进行渲染?

如果这不可能(或不切实际),如何将PNG保存为带alpha通道的真彩色图像。我尝试过ImageMagick:

convert image.png -depth 32 image.png

但图像似乎仍然保存为索引彩色图像

作为一些额外的背景信息 - 该程序正在使用SDL1.2,但在移植到SDL2后停止工作。我已将其他所有内容更新为SDL2,但SDL2_image的工作方式可能发生了变化,我不知道。

3 个答案:

答案 0 :(得分:2)

只需使用SDL_ConvertSurfaceFormat() ...

将其转换为正确的格式
SDL_Surface *image = ...;
SDL_Surface *converted = SDL_ConvertSurfaceFormat(
    image, SDL_PIXELFORMAT_ARGB8888, 0);

答案 1 :(得分:1)

您可以强制ImageMagick创建一个32位图像(即每个通道8位加alpha),如下所示:

convert image.png PNG32:image.png

答案 2 :(得分:0)

在ImageMagick奇怪的语言下,索引图像只是一个带有"颜色类型" 3号(调色板)。

因此,要使用convert命令生成不带调色板的png,您必须:

convert -type TrueColorAlpha image_in.png image_out.png