Read me About Demoscene? Links Contact

Code snippet for loading textures

Yeah, well. Loading textures is something that has to be done and over the years I have used a variety of different image loading libraries like devIL, sdl_image, etc. They are all great but mostly require an extra external dll residing next to the compiled binary.

To remove the dependency on external dll’s I’ve found a public domain image loader by Sean Barett. It loads jpg, png, bmp, tga and psds and consists of a single file that could be split into a .h and .c file.

Using the library for loading textures into OpenGL can be done very easily like this:

namespace ImageLoader

{

	unsigned int Load(const char* imgfilename, const char* folder)

	{

		unsigned int id=0;



		glPushAttrib(GL_TEXTURE_2D);

		glEnable(GL_TEXTURE_2D);

		int width, height, components;

		char name[_MAX_PATH];

		sprintf(name, "%s/%s", folder, imgfilename);

		unsigned char * data = stbi_load(name, &width, &height, &components, 4);

		if (data) 

		{

			glGenTextures(1, &id);

			glBindTexture(GL_TEXTURE_2D, id);

			glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

			glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

			glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

		}

		else

		{

			char buffer[8192];

			sprintf(buffer, "Error loading '%s'\n", name);

			OutputDebugString(buffer);

		}

		stbi_image_free(data);

		glDisable(GL_TEXTURE_2D);

		glPopAttrib();



		return id;

	}

}