2016-04-29 149 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