如何在GLUT上加载bmp以将其用作纹理?

Pat*_*erí 17 c++ opengl glut textures bmp

我一直在寻找一个简单的解决方案,用c ++为我的OpenGl GLUT简单月球着陆器游戏添加精灵,看来我必须使用bmp,因为它们最容易加载并将它们用作矩形上的纹理.

我怎样才能将bmp作为纹理加载?

Din*_*edi 33

看看我的简单c实现函数来加载纹理.

GLuint LoadTexture( const char * filename )
{

  GLuint texture;

  int width, height;

  unsigned char * data;

  FILE * file;

  file = fopen( filename, "rb" );

  if ( file == NULL ) return 0;
  width = 1024;
  height = 512;
  data = (unsigned char *)malloc( width * height * 3 );
  //int size = fseek(file,);
  fread( data, width * height * 3, 1, file );
  fclose( file );

 for(int i = 0; i < width * height ; ++i)
{
   int index = i*3;
   unsigned char B,R;
   B = data[index];
   R = data[index+2];

   data[index] = R;
   data[index+2] = B;

}


glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST );


glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE, data );
free( data );

return texture;
}
Run Code Online (Sandbox Code Playgroud)

上面的函数返回纹理数据.将纹理数据存储在变量中

 GLuint texture
 texture= LoadTexture( "your_image_name.bmp" );
Run Code Online (Sandbox Code Playgroud)

现在您可以使用glBindTexture绑定texure

glBindTexture (GL_TEXTURE_2D, texture);
Run Code Online (Sandbox Code Playgroud)

  • 我使用你的代码在我的程序中实现图像。它加载 bmp 文件,但没有在屏幕上显示任何内容。 (4认同)
  • 这是线程不安全的 (2认同)
  • 嗯,请注意这只适用于没有标题的图像 (2认同)
  • 虽然你可以抛出额外的fread(数据,54,1,文件)来剥离典型的BMP缓冲区...... (2认同)