2016-04-29 111 views
0

我已纹理与.bmp格式图像的球体。问题是,当图像映射到球体上时,图像的颜色看起来反转。就像红色变成蓝色,蓝色变成红色。 我试过用GL_BGR而不是GL_RGB但没用。 我是否必须更改加载图像的代码。因为它会产生使用功能的警告,我也不认为它与我所要求的相关。 映射后我得到的图像是texured sphere with inverted colors纹理加载和映射

这是我试图加载图像和应用一些纹理渲染的东西。

GLuint LoadTexture(const char * filename, int width, int height) 
{ 
GLuint texture; 
unsigned char * data; 
FILE * file; 

//The following code will read in our RAW file 
file = fopen(filename, "rb"); 
if (file == NULL) return 0; 
data = (unsigned char *)malloc(width * height * 3); 
fread(data, width * height * 3, 1, file); 
fclose(file); 

glGenTextures(1, &texture); //generate the texturewith the loaded data 
glBindTexture(GL_TEXTURE_2D, texture); //bind thetexture to it’s array 
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE); //set  texture environment parameters 




// better quality 
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR); 
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); 

//Here we are setting the parameter to repeat the textureinstead of clamping the texture 
//to the edge of our shape. 
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT); 
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT); 

//Generate the texture with mipmaps 
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE, data); 
free(data); //free the texture 
return texture; //return whether it was successfull 
} 

    void FreeTexture(GLuint texture) 
    { 
    glDeleteTextures(1, &texture); 
    } 
+0

[如何在GLUT上加载bmp以将其用作纹理?](http://stackoverflow.com/questions/12518111/how-to-load-a-bmp-on-glut-使用它作为一个纹理) – teivaz

回答

0

BMP文件开始以BITMAPFILEHEADER结构,其中包含(除其他事项外)偏移到该文件中的比特的实际开始。

所以你可以做这样的事情来获取BMP文件的位。

BITMAPFILEHEADER bmpFileHeader; 
fread(&bmpFileHeader,sizeof(bmpFileHeader),1,file); 
fsetpos(file,bmpFileHeader->bfOffBits,SEEK_SET); 
size_t bufferSize = width * height * 3; 
fread(data,bufferSize,1,file); 

当然,这是很危险的,因为您期待正确大小和格式化的BMP文件。所以你真的需要阅读BITMAPINFO。

BITMAPFILEHEADER bmpFileHeader; 
fread(&bmpFileHeader,sizeof(bmpFileHeader),1,file); 
BITMAPINFO bmpInfo; 
fread(&bmpInfo,sizeof(bmpInfo),1,file) 
fsetpos(file,bmpFileHeader->bfOffBits,SEEK_SET); 
int width = bmpInfo->bmiHeader.biWidth; 
int height = bmpInfo->bmiHeader.biHeight; 
assert(bmpInfo->bmiHeader.biCompression == BI_RGB); 
assert(bmpInfo->bmiHeader.biBitCount == 24; 
size_t bufferSize = width * height * 3; 
fread(data,bufferSize,1,file); 

你可以明显地将bmp格式映射到允许的opengl格式。

其他并发症是:

  • bmp的数据是自下而上因此,除非您纠正将出现颠倒。
  • 填充bmp文件中的像素数据以确保每行都是4个字节宽的倍数,如果图像不是32位/像素或4像素宽的倍数,则会导致步幅问题通常是真的)。
  • 仅仅因为你可以向OpenGL提供一个常量并不意味着格式实际上被支持。有时你只需进入并重新排序字节。
+0

因为我在这个领域是新的告诉我BITMAPFILEHEADER是glut.h中可用,或者我必须为此添加一些特定的头文件。 – saurabh

+0

哦,我看到了 - 你不是在窗户上这样做?如果你是,只要#include ,如果没有,你可以找到这里记录的BMP文件结构:https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85) 。aspx –

+0

好的。我通过编辑修正了颠倒的图像。 – saurabh