http://blog.chinaunix.net/u1/56532/showart_1361031.html本来自己写了一个读图像的类(仅限BMP格式),后来无意中认识了FreeImage。于是,把代码稍微改改,就可以读取27种格式的图像了。呵呵,这个对于我来说真是太方便了。一切为了OGL嘛~
下面是代码:
Load2DTextures.h: #include <gl/glut.h>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <freeimage.h>
class CLoad2DTextures
{
public:
CLoad2DTextures(void);
~CLoad2DTextures(void);
public:
BOOL LoadTextures(char **nameList,GLuint *texturesID,int num,GLenum filter=GL_NEAREST,
GLenum wrapS=GL_REPEAT,GLenum wrapT=GL_REPEAT,
GLenum envMode=GL_MODULATE);
};
Load2DTextures.cpp: #include "Load2DTextures.h"
CLoad2DTextures::CLoad2DTextures(void)
{
FreeImage_Initialise(FALSE);
}
CLoad2DTextures::~CLoad2DTextures(void)
{
FreeImage_DeInitialise();
}
BOOL CLoad2DTextures::LoadTextures(char **nameList, GLuint *texturesID, int num, GLenum filter, GLenum wrapS, GLenum wrapT, GLenum envMode)
{
unsigned int width;
unsigned int height;
unsigned char *imageData;
unsigned char temp;
unsigned int i;
unsigned int index;
FIBITMAP *image;
FREE_IMAGE_FORMAT ff;
//glPixelStorei(GL_UNPACK_ALIGNMENT,1);//这句话貌似没用,注释先~
for(i=0;i<num;i++)
{
glGenTextures(1,&texturesID[i]);
glBindTexture(GL_TEXTURE_2D,texturesID[i]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,filter);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,filter);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,wrapS);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,wrapT);
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,envMode);
ff =
FreeImage_GetFileType(nameList[i],0);
if(!(image =
FreeImage_Load(ff,nameList[i],0)))
{
MessageBox(NULL,"无法加载指定纹理!","错误",MB_OK|MB_ICONEXCLAMATION);
return FALSE;
}
image =
FreeImage_ConvertTo24Bits(image);//使用24位图操作;
imageData = (unsigned char *)
FreeImage_GetBits(image);//获取图像位信息;
width =
FreeImage_GetWidth(image);
height =
FreeImage_GetHeight(image);
for(index=0;index<width*height*3;index+=3)//BGR -> RGB 转换
{
temp = imageData[index];
imageData[index] = imageData[index+2];
imageData[index+2] = temp;
}
//下面就开始Build MipMaps了~
gluBuild2DMipmaps(GL_TEXTURE_2D,GL_RGB,width,height,GL_RGB,GL_UNSIGNED_BYTE,imageData);
FreeImage_Unload(image);//贴图搞定,最后别忘了释放掉你的资源~
}
return TRUE;
}
//在VC9里做的,在X里也大同小异了。其实,VC9功能还挺不错,呵呵,我还是喜欢VIM~