Skip to content

Instantly share code, notes, and snippets.

@akyoto
Created July 11, 2012 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akyoto/3089309 to your computer and use it in GitHub Desktop.
Save akyoto/3089309 to your computer and use it in GitHub Desktop.
BPTextureInfo *flua_loadTexture(
const char* filename,
GLenum image_format,
GLint internal_format,
GLint level,
GLint border
) {
//image format
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
//pointer to the image, once loaded
FIBITMAP* dib(0);
//pointer to the image data
BYTE* bits(0);
//image width and height
unsigned int width(0), height(0);
//OpenGL's image ID to map to
GLuint gl_texID;
//check the file signature and deduce its format
fif = FreeImage_GetFileType(filename, 0);
//if still unknown, try to guess the file format from the file extension
if(fif == FIF_UNKNOWN)
fif = FreeImage_GetFIFFromFilename(filename);
//if still unkown, return failure
if(fif == FIF_UNKNOWN)
return NULL;
//check that the plugin has reading capabilities and load the file
if(FreeImage_FIFSupportsReading(fif))
dib = FreeImage_Load(fif, filename);
//if the image failed to load, return failure
if(!dib)
return NULL;
//retrieve the image data
bits = FreeImage_GetBits(dib);
//get the image width and height
width = FreeImage_GetWidth(dib);
height = FreeImage_GetHeight(dib);
//if this somehow one of these failed (they shouldn't), return failure
if((bits == 0) || (width == 0) || (height == 0))
return NULL;
//generate an OpenGL texture ID for this texture
glGenTextures(1, &gl_texID);
//bind to the new texture ID
glBindTexture(GL_TEXTURE_2D, gl_texID);
//store the texture data for OpenGL use
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, level, internal_format, width, height, border, image_format, GL_UNSIGNED_BYTE, bits);
gluBuild2DMipmaps(GL_TEXTURE_2D, internal_format, width, height, image_format, GL_UNSIGNED_BYTE, bits);
//Free FreeImage's copy of the data
// TODO: This should not lead to a segfault
FreeImage_Unload(dib);
//return success
return new (UseGC) BPTextureInfo(gl_texID, width, height);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment