OpenGL本身没有文件操作有关的接口,需要使用第三方库。这里使用DevIL库。
下载连接:http://openil.sourceforge.net/download.php
下载DevIL-Windows-SDK,解压后在Visual Studio配置头文件位置、lib库位置、lib库名称,拷贝dll库到当前工程。
LTexture.cpp
bool LTexture::loadTextureFromFile( std::string path )
{
bool textureLoaded = false;
ILuint imgID = 0;
ilGenImages( 1, &imgID );//生成图像ID
ilBindImage( imgID );//绑定
ILboolean success = ilLoadImage( path.c_str() );//加载图片
if( success == IL_TRUE )
{
success = ilConvertImage( IL_RGBA, IL_UNSIGNED_BYTE );//转换为rgba像素格式
if( success == IL_TRUE )
{
textureLoaded = loadTextureFromPixels32( (GLuint*)ilGetData(), (GLuint)ilGetInteger( IL_IMAGE_WIDTH ), (GLuint)ilGetInteger( IL_IMAGE_HEIGHT ) );//根据图片的像素去创建纹理,ilGetData()方法获取图片的像素
}
ilDeleteImages( 1, &imgID );//从内存删除即回收该图片。DevIL和OpenGL有着类似的状态机机制,即先生成并绑定ID,然后进行各做操作,最后解除绑定
}
if( !textureLoaded )
{
printf( "Unable to load %s
", path.c_str() );
}
return textureLoaded;
}
LUtil.cpp
bool initGL()
{
...
ilInit();//初始化devil
ilClearColour( 255, 255, 255, 000 );//设置devil自己的渲染清屏颜色
ILenum ilError = ilGetError();
if( ilError != IL_NO_ERROR )
{
printf( "Error initializing DevIL! %s
", iluErrorString( ilError ) );
return false;
}
return true;
}
bool loadMedia()
{
if( !gLoadedTexture.loadTextureFromFile( "texture.png" ) )
{
printf( "Unable to load file texture!
" );
return false;
}
return true;
}