FreeImage+openGL

来源:互联网 发布:win10平板软件下载 编辑:程序博客网 时间:2024/06/16 14:00

最近一直重拾自己以前做的东西,心中有个想法,想实现。当载入图片的时候用的是FreeImage,FreeImage是比较好用的库,不说了 以下见源代码。“TextureManage.h”和“TextureManage.cpp”是FreeImage库中自带的程序,main函数是结合了openGL写的。

TextureManager.h

//**********************************************//Singleton Texture Manager class//Written by Ben English//benjamin.english@oit.edu////For use with OpenGL and the FreeImage library//**********************************************#ifndef TextureManager_H#define TextureManager_H//#define GLUT_DISABLE_ATEXIT_HACK #include <windows.h>#include <gl/gl.h>#include "FreeImage.h"#include <map>class TextureManager{public:static TextureManager* Inst();virtual ~TextureManager();//加载一个纹理,变为当前纹理,如果texID已经被使用,不加载或者替换掉这个纹理bool LoadTexture(const char* filename,//where to load the file fromconst unsigned int texID,//arbitrary id you will reference the texture by//does not have to be generated with glGenTexturesGLenum image_format = GL_RGB,//format the image is inGLint internal_format = GL_RGB,//format to store the image inGLint level = 0,//mipmapping levelGLint border = 0);//border size//释放纹理内存bool UnloadTexture(const unsigned int texID);//设置当前的纹理bool BindTexture(const unsigned int texID);//释放所有纹理内存void UnloadAllTextures();protected:TextureManager();TextureManager(const TextureManager& tm);TextureManager& operator=(const TextureManager& tm);static TextureManager* m_inst;std::map<unsigned int, GLuint> m_texID;};#endif

TextureManager.cpp

//**********************************************//Singleton Texture Manager class//Written by Ben English//benjamin.english@oit.edu////For use with OpenGL and the FreeImage library//**********************************************#include "TextureManager.h"TextureManager* TextureManager::m_inst(0);TextureManager* TextureManager::Inst(){if(!m_inst)m_inst = new TextureManager();return m_inst;}TextureManager::TextureManager(){// call this ONLY when linking with FreeImage as a static library#ifdef FREEIMAGE_LIBFreeImage_Initialise();#endif}//these should never be called//TextureManager::TextureManager(const TextureManager& tm){}//TextureManager& TextureManager::operator=(const TextureManager& tm){}TextureManager::~TextureManager(){// call this ONLY when linking with FreeImage as a static library#ifdef FREEIMAGE_LIBFreeImage_DeInitialise();#endifUnloadAllTextures();m_inst = 0;}bool TextureManager::LoadTexture(const char* filename, const unsigned int texID, GLenum image_format, GLint internal_format, GLint level, GLint border){//image formatFREE_IMAGE_FORMAT fif = FIF_UNKNOWN;//pointer to the image, once loadedFIBITMAP *dib(0);//pointer to the image dataBYTE* bits(0);//image width and heightunsigned int width(0), height(0);//OpenGL's image ID to map toGLuint gl_texID;//check the file signature and deduce its formatfif = FreeImage_GetFileType(filename, 0);//if still unknown, try to guess the file format from the file extensionif(fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(filename);//if still unkown, return failureif(fif == FIF_UNKNOWN)return false;//check that the plugin has reading capabilities and load the fileif(FreeImage_FIFSupportsReading(fif))dib = FreeImage_Load(fif, filename);//if the image failed to load, return failureif(!dib)return false;//retrieve the image databits = FreeImage_GetBits(dib);//get the image width and heightwidth = FreeImage_GetWidth(dib);height = FreeImage_GetHeight(dib);//if this somehow one of these failed (they shouldn't), return failureif((bits == 0) || (width == 0) || (height == 0))return false;//if this texture ID is in use, unload the current textureif(m_texID.find(texID) != m_texID.end())glDeleteTextures(1, &(m_texID[texID]));//generate an OpenGL texture ID for this textureglGenTextures(1, &gl_texID);//store the texture ID mappingm_texID[texID] = gl_texID;//bind to the new texture IDglBindTexture(GL_TEXTURE_2D, gl_texID);//store the texture data for OpenGL useglTexImage2D(GL_TEXTURE_2D, level, internal_format, width, height,border, image_format, GL_UNSIGNED_BYTE, bits);//Free FreeImage's copy of the dataFreeImage_Unload(dib);//return successreturn true;}bool TextureManager::UnloadTexture(const unsigned int texID){bool result(true);//if this texture ID mapped, unload it's texture, and remove it from the mapif(m_texID.find(texID) != m_texID.end()){glDeleteTextures(1, &(m_texID[texID]));m_texID.erase(texID);}//otherwise, unload failedelse{result = false;}return result;}bool TextureManager::BindTexture(const unsigned int texID){bool result(true);//if this texture ID mapped, bind it's texture as currentif(m_texID.find(texID) != m_texID.end())glBindTexture(GL_TEXTURE_2D, m_texID[texID]);//otherwise, binding failedelseresult = false;return result;}void TextureManager::UnloadAllTextures(){//start at the begginning of the texture mapstd::map<unsigned int, GLuint>::iterator i = m_texID.begin();//Unload the textures untill the end of the texture map is foundwhile(i != m_texID.end())UnloadTexture(i->first);//clear the texture mapm_texID.clear();}
main.cpp

#include <gl/glut.h>#include "TextureManager.h"#define GLUT_DISABLE_ATEXIT_HACK//全局贴图IDGLuint texture[1];void init(){//将2D贴图状态打开glEnable( GL_TEXTURE_2D );//单件贴图管理//如果加载带路径的文件最好选用../这样的格式TextureManager::Inst()->LoadTexture( "1.jpg", texture[0] );//线性过滤一定要放到加载纹理的后面glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);    // 线性滤波glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);    // 线性滤波glClearColor( 0.5, 0.5, 0.5, 0.5 );}void display(){glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );//绑定纹理TextureManager::Inst()->BindTexture( texture[0] );//渲染glBegin( GL_QUADS );glTexCoord2d( 0, 0 ); glVertex3f( -7.0f, -7.0f, 0.0f );glTexCoord2d( 0, 1 ); glVertex3f( -7.0f, 7.0f, 0.0f );glTexCoord2d( 1, 1 ); glVertex3f( 7.0f, 7.0f, 0.0f );glTexCoord2d( 1, 0 ); glVertex3f( 7.0f, -7.0f, 0.0f );glEnd();glFlush();glutSwapBuffers();}void reshape( int w, int h ){glViewport( 0, 0, GLsizei( w ), GLsizei( h ) );glMatrixMode( GL_PROJECTION );glLoadIdentity();gluPerspective( 45, ( GLdouble ) w / ( GLdouble ) h, 1.0f, 1000.0f );glMatrixMode( GL_MODELVIEW );glLoadIdentity();gluLookAt( 0, 0, 20, 0, 0, 0, 0, 1, 0 );}void keyboard( unsigned char key, int x, int y ){if ( key == 27 ){//释放掉贴图,防止内存泄露TextureManager::Inst()->UnloadTexture( texture[0] );exit( 0 );}}int main( int argc, char *argv[] ){glutInit( &argc, argv );glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH );glutInitWindowPosition( 300, 300 );glutInitWindowSize( 400, 300 );glutCreateWindow( "OpenGL Texture Test" );init();glutReshapeFunc( reshape );glutKeyboardFunc( keyboard );glutDisplayFunc( display );glutMainLoop();return 0;}




#include<GL/glut.h>#include "FreeImage.h"#include <Windows.h>char* bmpfile[1]=//{("Data/Particle.bmp")};{"H:\\program\\1\\Data\\Particle.bmp"};int w=500,h=500;GLuint texture[1];GLenum image_format = GL_BGR_EXT;        //format the image is inGLint internal_format = GL_RGB;        //format to store the image inGLint level = 0;                   //mipmapping levelGLint border = 0;FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;FIBITMAP *dib(0);//BYTE* bits(0);unsigned char *imageData;unsigned int width(0), height(0);bool LoadImage(const char*filename){#ifdef FREEIMAGE_LIBFreeImage_Initalise();#endifFIBITMAP *dib(0);fif = FreeImage_GetFileType(filename, 0);if(fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(filename);if(fif == FIF_UNKNOWN)return false;if(FreeImage_FIFSupportsReading(fif))dib = FreeImage_Load(fif, filename);if(!dib)return false;bool flipResult = FreeImage_FlipVertical(dib);dib = FreeImage_ConvertTo24Bits(dib);imageData = (unsigned char *)FreeImage_GetBits(dib);//获取图像位信息;/*bits = FreeImage_GetBits(dib);*/width = FreeImage_GetWidth(dib);height = FreeImage_GetHeight(dib);int p=FreeImage_GetBPP(dib);if((imageData == 0) || (width == 0) || (height == 0))return false;}void reshape(int  width,int  height)//调整和初始化GL的窗口{if (height==0)// Prevent A Divide By Zero By{height=1;// Making Height Equal One}glViewport(0,0,width,height);// Reset The Current ViewportglMatrixMode(GL_PROJECTION);// Select The Projection MatrixglLoadIdentity();// Reset The Projection MatrixglOrtho(0,w,0,h,-10.1,100);glMatrixMode(GL_MODELVIEW);// Select The Modelview MatrixglLoadIdentity();// Reset The Modelview Matrix//gluLookAt(0.0,0.0,40.0,0.0,0.0,0.0,0.0,1.0,0.0);w=width;h=height;}int Init(void){glClearColor(1.0,1.0,1.0,1.0);glShadeModel(GL_SMOOTH);if(!LoadImage(bmpfile[0])){return false;    }glGenTextures(1,&texture[0]);glBindTexture(GL_TEXTURE_2D,texture[0]);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);glTexImage2D(GL_TEXTURE_2D, level, internal_format, width, height,border, image_format, GL_UNSIGNED_BYTE, imageData);return true;}void display(){glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen And The Depth BufferglEnable(GL_TEXTURE_2D);glColor3f(1.0,0.0,1.0);//glMatrixMode( GL_MODELVIEW );//glLoadIdentity();// Reset The ViewglBindTexture(GL_TEXTURE_2D,texture[0]);glBegin(GL_QUADS);glNormal3f( 0.0f, 0.0f, 0.0f);glTexCoord2f(0.0f, 0.0f);glVertex3f(0,0,0); //glVertex3f(-w/2.0,-h/2.0, 0.0f);glTexCoord2f(1.0f, 0.0f); glVertex3f(w/2,0,0); //glVertex3f(w/2.0,-h/2.0, 0.0f);glTexCoord2f(1.0f, 1.0f); glVertex3f(w/2,h/2,0); //glVertex3f( w/2, h/2, 0.0f);glTexCoord2f(0.0f, 1.0f);glVertex3f(0,h/2,0); //glVertex3f(-w/2, h/2, 0.0f);glEnd();glFlush();glDisable(GL_TEXTURE_2D);}int main(int argc,char **argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);glutInitWindowSize(500,500);glutCreateWindow(argv[0]);Init();glutReshapeFunc(reshape);glutDisplayFunc(display);glutMainLoop();return 0;}

#include<GL/glut.h>#include "FreeImage.h"#include <Windows.h>char* bmpfile[2]={("Data/snow.png"),("Data/3.jpg")};//{//("H:\\program\\1\\Data\\2.bmp"),("H:\\program\\1\\Data\\snow.bmp")};int w=500,h=500;GLuint texture[2];GLenum image_format = GL_BGR_EXT;        //format the image is inGLint internal_format = GL_RGB;        //format to store the image inGLint level = 0;                   //mipmapping levelGLint border = 0;FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;FIBITMAP *dib(0);//BYTE* bits(0);unsigned char *imageData;unsigned int width(0), height(0);typedef struct Position{   float x;   float y;   float z;   float ax;   float ay;   float az;   float angle;};Position Sphere;bool LoadImage(const char*filename){#ifdef FREEIMAGE_LIBFreeImage_Initalise();#endifFIBITMAP *dib(0);int index1;int temp;fif = FreeImage_GetFileType(filename, 0);if(fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(filename);if(fif == FIF_UNKNOWN)return false;if(FreeImage_FIFSupportsReading(fif))dib = FreeImage_Load(fif, filename);if(!dib)return false;bool flipResult = FreeImage_FlipVertical(dib);dib = FreeImage_ConvertTo24Bits(dib);imageData = (unsigned char *)FreeImage_GetBits(dib);//获取图像位信息;/*bits = FreeImage_GetBits(dib);*/width = FreeImage_GetWidth(dib);height = FreeImage_GetHeight(dib);int p=FreeImage_GetBPP(dib);if((imageData == 0) || (width == 0) || (height == 0))return false;}void reshape(int  width,int  height)//调整和初始化GL的窗口{if (height==0)// Prevent A Divide By Zero By{height=1;// Making Height Equal One}glViewport(0,0,width,height);// Reset The Current ViewportglMatrixMode(GL_PROJECTION);// Select The Projection MatrixglLoadIdentity();// Reset The Projection MatrixglOrtho(0,w,0,h,-10.1,100);glMatrixMode(GL_MODELVIEW);// Select The Modelview MatrixglLoadIdentity();// Reset The Modelview Matrix//gluLookAt(0.0,0.0,40.0,0.0,0.0,0.0,0.0,1.0,0.0);w=width;h=height;}int Init(void){glClearColor(0.0,0.0,0.0,0.0);glShadeModel(GL_SMOOTH);for(int i=0;i<2;++i){if(!LoadImage(bmpfile[i])){return false;    }glGenTextures(1,&texture[i]);glBindTexture(GL_TEXTURE_2D,texture[i]);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);glTexImage2D(GL_TEXTURE_2D, level, internal_format, width, height,border, image_format, GL_UNSIGNED_BYTE, imageData);}Sphere.ax=1.0;Sphere.ay=1.0;Sphere.az=0.0;Sphere.x=300.0;Sphere.y=500.0;Sphere.z=0.0;Sphere.angle=1.0;return true;}void display(){glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear The Screen And The Depth BufferglEnable(GL_TEXTURE_2D);  glColor3f(1.0,1.0,1.0);glMatrixMode( GL_MODELVIEW );glLoadIdentity();// Reset The ViewglBindTexture(GL_TEXTURE_2D,texture[0]);glBegin(GL_QUADS);glNormal3f( 0.0f, 0.0f, 0.0f);glTexCoord2f(0.0f, 0.0f);glVertex3f(0,h,0); //glVertex3f(-w/2.0,-h/2.0, 0.0f);glTexCoord2f(1.0f, 0.0f); glVertex3f(w,h,0); //glVertex3f(w/2.0,-h/2.0, 0.0f);glTexCoord2f(1.0f, 1.0f); glVertex3f(w,0,0); //glVertex3f( w/2, h/2, 0.0f);glTexCoord2f(0.0f, 1.0f);glVertex3f(0,0,0); //glVertex3f(-w/2, h/2, 0.0f);glEnd();glPushMatrix();glBindTexture(GL_TEXTURE_2D,texture[1]);glBegin(GL_QUADS);//glEnable(GL_BLEND);//glBlendFunc(GL_ZERO, GL_ONE ); //glEnable(GL_BLEND);//glColor4f(1.0f,1.0f,1.0f,0.5f);//glBlendFunc(GL_SRC_ALPHA,GL_ONE);glTranslatef(Sphere.x,Sphere.y,Sphere.z);glRotated(Sphere.angle,0.0f,0.0f,1.0f);glNormal3f( 0.0f, 0.0f, 0.0f);glTexCoord2f(0.0f, 0.0f);//glVertex3f(0,h/10,0); glVertex3f(Sphere.x-50,Sphere.y+50, 0.0f);glTexCoord2f(1.0f, 0.0f); //glVertex3f(w/10,h/10,0); glVertex3f(Sphere.x+50,Sphere.y+50, 0.0f);glTexCoord2f(1.0f, 1.0f); //glVertex3f(w/10,0,0); glVertex3f(Sphere.x+50,Sphere.y-50, 0.0f);glTexCoord2f(0.0f, 1.0f);//glVertex3f(0,0,0); glVertex3f(Sphere.x-50,Sphere.y-50, 0.0f);glEnd();glPopMatrix();/*glPushMatrix();glColor3f(0.0,0.0,1.0);glTranslatef(Sphere.x,Sphere.y,Sphere.z);glutSolidSphere(40,32,20);glRotated(Sphere.angle,0.0f,1.0f,1.0f);glPopMatrix();*/glutSwapBuffers();glDisable(GL_TEXTURE_2D);}void idle(){   // Sphere.x+=Sphere.ax;Sphere.y-=Sphere.ay;//Sphere.z+=Sphere.az;Sphere.angle += 1.0f;if( Sphere.angle >= 360.0f )Sphere.angle = 0.0f;display();}int main(int argc,char **argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);glutInitWindowSize(500,500);glutCreateWindow(argv[0]);Init();glutReshapeFunc(reshape);glutDisplayFunc(display);glutIdleFunc(idle);glutMainLoop();return 0;}


原创粉丝点击