OpenGL第六节:加载png图片

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\n", 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\n", iluErrorString( ilError ) );
    return false;
  }

  return true;

}

bool loadMedia()
{
  if( !gLoadedTexture.loadTextureFromFile( "texture.png" ) )
  {
    printf( "Unable to load file texture!\n" );
    return false;
  }

  return true;
}

 

posted @   yongfengnice  阅读(938)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示