SDL_image是比较好用的图像处理库之一,支持bmp, jpg, tga, png等多种图片格式的加载(目前不支持dds)。不过使用SDL_image有一些细节问题需要格外注意.
操作系统: Windows XP SP3
编译环境: Visual Studio 2005
点击VS菜单栏的项目->XXX属性->配置属性->链接器->系统->子系统,选择”控制台(/SUBSYSTEM:CONSOLE)“。这一步必须设置好,否则将出现:
fatal error LNK1561:必须定义入口点
这个错误。
头文件:
#include "sdl/include/SDL.h"
#include "sdl/include/SDL_main.h"
#include "sdl/include/SDL_image.h"
静态链接库:
#pragma comment(lib,"sdl/lib/SDL.lib")
#pragma comment(lib,"sdl/lib/SDLmain.lib")
#pragma comment(lib,"sdl/lib/SDL_image.lib")
图片加载函数:
// Load image file using the SDL_image library, the image file format can be bmp, jpg, tga, png and so on. GLvoid LoadImage(char *filename, GLuint &texture) { SDL_Surface *image; SDL_Rect area; Uint32 saved_flags; Uint8 saved_alpha; SDL_Surface *pSurface = IMG_Load(filename); image = SDL_CreateRGBSurface( SDL_SWSURFACE, pSurface->w, pSurface->h, 32, #if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */ 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); if ( image == NULL ) { MessageBox(NULL, "SDL Create Surface Error!", "ERROR", MB_OK | MB_ICONEXCLAMATION); return; } /* Save the alpha blending attributes */ saved_flags = pSurface->flags&(SDL_SRCALPHA|SDL_RLEACCELOK); saved_alpha = pSurface->format->alpha; if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { SDL_SetAlpha(pSurface, 0, 0); } /* Copy the surface into the GL texture image */ area.x = 0; area.y = 0; area.w = pSurface->w; area.h = pSurface->h; SDL_BlitSurface(pSurface, &area, image, &area); /* Restore the alpha blending attributes */ if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { SDL_SetAlpha(pSurface, saved_flags, saved_alpha); } /* Create an OpenGL texture for the image */ glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); // glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // glTexImage2D(GL_TEXTURE_2D, // 0, // GL_RGBA, // image->w, image->h, // 0, // GL_RGBA, // GL_UNSIGNED_BYTE, // image->pixels); gluBuild2DMipmaps(GL_TEXTURE_2D, 4, image->w, image->h, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels); SDL_FreeSurface(image); /* No longer needed */ }