一、简介
看Nehe的教程学习OpenGL看到加载图片时用到了FreeImage,跟着写了下,发现图片颜色是错乱的。
如图:
调试的时候发现自己的少了一段代码:
if ((imageType == FIT_BITMAP) && (FreeImage_GetBPP(pBitmap) == 24))
{
textureFormat = GL_RGBA;
datatype = GL_UNSIGNED_BYTE;
components = GL_RGBA;
texturedata = (unsigned char*)malloc(nWidth*nHeight*4);
int red, green, blue, alpha;
#ifdef BIG_ENDIAN//! RGBA;
red = 0; green = 1; blue = 2; alpha = 3;
#else//! BGRA;
red = 2; green = 1; blue = 0; alpha = 3;
#endif
int offset = 0;
int offset_img = 0;
for (unsigned int y = 0; y < nHeight; y++)
{
for (unsigned int x = 0; x < nWidth; x++)
{
texturedata[offset+red] = ((unsigned char*)bits)[offset_img+0];
texturedata[offset+green] = ((unsigned char*)bits)[offset_img+1];
texturedata[offset+blue] = ((unsigned char*)bits)[offset_img+2];
texturedata[offset+alpha] = 0;
offset += 4;
offset_img += 3;
}
offset_img = y*nPitch;
}
}
原来BMP格式图片是按blue,green,red顺序存储的,而不是OpenGL常见的R,G,B顺序。
二、解决方法
1.读取数据的时候把数据按需要的方式读取,像NeHe处理代码类似.
2.不想那么麻烦可以,可以直接用OpenGL定义的转换方式转换,只需改一个参数:
(修改红色字体部分,第7个参数):
glTexImage2D(GL_TEXTURE_2D, level, internal_format, width, height,
border, GL_BGR_EXT, GL_UNSIGNED_BYTE, bits);//GL_RGB转 GL_BGR_EXT;
border, GL_BGR_EXT, GL_UNSIGNED_BYTE, bits);//GL_RGB转 GL_BGR_EXT;
效果如图: