opengl 加载bmp做纹理

在学习OPENGL过程中,红皮书上的例子纹理都是现生成的方格图片,太难看,今天在网上找到一个方法,可以很方便的加载你想要的图片,感谢此方法的编写者(忘记了出处,请原谅!)。

//注意:width height要与实际图片相同;另外filename必须指向BMP图片,其它编码格式请先转码

GLuint LoadTexture( const char * filename, int width, int height )

    {
GLuint texture;
unsigned char * data;
FILE * file;

//The following code will read in our PNG 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 texture with 

glBindTexture( GL_TEXTURE_2D, texture ); //bind the texture

glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, 
GL_MODULATE ); //set texture environment parameters

//even better quality, but this will do for now.
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR );


//Here we are setting the parameter to repeat 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
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
GL_RGB, GL_UNSIGNED_BYTE, data);
free( data ); //free the texture
return texture; //return whether it was successfull
}

你可能感兴趣的:(OpenGL,opengl,texture)