如标题所示,加载.tga文件时遇到了问题。我一直在使用this作为引用,据我所知(除了使用c++函数而不是c函数),我正在做同样的事情。我确实得到了纹理,但这是应该显示的乱码,我不确定为什么。请原谅所有错误,我只是想让它正常工作。
header :
struct TGA
{
GLuint Load(const char* filename);
unsigned char header_[12];
unsigned char bpp_;
unsigned char id_;
unsigned short width_;
unsigned short height_;
unsigned char* data_;
};
Cpp:
GLuint TGA::Load(const char* filename)
{
width_ = 0; height_ = 0;
bpp_ = 32; id_ = 8;
data_ = 0;
std::ifstream file;
file.open(filename, std::ios::binary | std::ios::ate);
if(file.fail())
{
std::cout<<filename<<" could not be opened."<<std::endl;
return 0;
}
file.seekg(0, std::ios::beg);
file.read((char*)header_, sizeof(unsigned char)*12);
file.read((char*)&width_, sizeof(unsigned short));
file.read((char*)&height_, sizeof(unsigned short));
file.read((char*)&bpp_, sizeof(unsigned char));
file.read((char*)&id_, sizeof(unsigned char));
int imageSize = width_ * height_;
std::cout<<imageSize<<std::endl;
data_ = new unsigned char[imageSize * 3]; //3 means RGB
file.read((char*)data_, imageSize * 3);
file.close();
GLuint texture;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_, height_, 0, GL_BGRA, GL_UNSIGNED_BYTE, data_);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width_, height_, GL_RGBA, GL_UNSIGNED_BYTE, data_);
delete [] data_;
return texture;
}
最佳答案
当您读入数据时,您假定targa文件每像素具有24位(file.read((char*)data_, imageSize * 3)
),而不检查bpp_
的值。然后,您将图像数据传递给OpenGL,并说您的数据为32 bpp BGRA格式。
您应该检查bpp_
的值是什么,根据该值分配和读取数据,并将正确的数据格式传递给OpenGL(BGR或BGRA,取决于图像中是否包含alpha通道)。
关于c++ - 加载Targa文件C++时出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9047073/