I am trying to load a texture into my small OpenGL app. I've seen a lot of recommendations for the stb library. It really fits my needs as it doesn't have to be built or linked, I can just include the header.
Unfortunately, I can't seem to get it to load a texture properly (on my Linux laptop or my Windows desktop). It finds the file correctly (because the dimensions properly fit whichever texture I am testing at the time) but it doesn't load the pixels correctly.
I first thought this was an error I was making with my OpenGL code, but upon further inspection of the array stb is returning to me, I have found that it is filled with 255 as every single value no matter what image I attempt to load.
Here is my texture loading code:
bool Texture::LoadTextureFromFile(std::string path)
{
bool success = true;
int comp, width, height;
unsigned char* image = stbi_load(path.c_str(), &width,
&height, &comp, 0);
texture_width = width;
texture_height = height;
glGenTextures(1, &texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
GL_UNSIGNED_BYTE, image);
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(image);
return success;
}
I have been banging my head against this for a week now, and would really love some enlightenment on the issue.
I can also present my OpenGL initialization code if anyone thinks that would help.
答案 0 :(得分:1)
你的opengl代码确实有错误。您必须在glGenTextures(1, &texture_id)
之后绑定纹理。我通过添加代码来工作(我还将RGB更改为RGBA,因为我使用的图像文件是RGBA格式)。
bool load(std::string filename) {
int w, h, comp;
GLuint t;
unsigned char * im = stbi_load(filename.c_str(), &w, &h, &comp, 0);
glGenTextures(1, &t);
glBindTexture(GL_TEXTURE_2D, t);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, im);
glBindTexture(GL_TEXTURE_2D, 0);
return true;
}
此代码适用于我。如果你说stbi_load只有255个值,你可能还有其他错误。确保您具有文件名的正确路径,并确保启用了纹理。