使用stb加载图像时出错

时间:2018-05-02 05:35:52

标签: c++ opengl graphics textures stb-image

我正在尝试加载以下图片:

enter image description here

作为斯坦福龙的纹理。结果如下: enter image description here

我已经读过其他人因为在加载纹理时没有正确绑定纹理或使用错误数量的组件而遇到问题。我认为我不会遇到这些问题,因为我正在检查图像的格式和绑定纹理。我已设法正确加载其他图像,所以这似乎有一个特定于此图像的问题(我不是说图像已损坏,而是关于此图像的某些内容与我尝试过的其他图像略有不同)

我用来初始化纹理的代码如下:

//Main constructor
Texture::Texture(string file_path, GLuint t_target)
{
    //Change the coordinate system of the image
    stbi_set_flip_vertically_on_load(true);
    int numComponents;
    //Load the pixel data of the image
    void *data = stbi_load(file_path.c_str(), &width, &height, &numComponents, 0);
    if (data == nullptr)//Error check
    {
        cerr << "Error when loading texture from file: " + file_path << endl;

        Log::record_log(
            string(80, '!') +
            "\nError when loading texture from file: " + file_path + "\n" +
            string(80, '!')
        );
        exit(EXIT_FAILURE);
    }
    //Create the texture OpenGL object
    target = t_target;
    glGenTextures(1, &textureID);
    glBindTexture(target, textureID);
    //Name the texture
    glObjectLabel(GL_TEXTURE, textureID, -1,
        ("\"" + extract_name(file_path) +"\"").c_str());
    //Set the color format
    color_format = numComponents == 3 ? GL_RGB : GL_RGBA;

    glTexImage2D(target, 0, color_format, width, height, 0,
        color_format, GL_UNSIGNED_BYTE, data);
    //Set the texture parameters of the image
    glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    //free the memory
    stbi_image_free(data);
    //Create a debug notification event
    char name[100];
    glGetObjectLabel(GL_TEXTURE, textureID, 100, NULL, name);
    string message = "Succesfully created texture: " + string(name) +
        ". Bound to target: " + textureTargetEnumToString(target);
    glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER, 0,
        GL_DEBUG_SEVERITY_NOTIFICATION, message.size(), message.c_str());
}

1 个答案:

答案 0 :(得分:1)

一个JPEG哇?可能没有alpha通道。并且894像素宽并非完全可被4整除。

仔细检查您是否正在点击numComponents == 3案例,如果是,请确保GL_UNPACK_ALIGNMENT设置为1(默认4){{在glPixelStorei()来电之前,请先填写。{/ p>