Sign in to follow this  

BitmapToTexture function

Recommended Posts

here's my function for converting a .bmp to a texture function. submitted not only for your approval, but your improvement. known issues: i eliminated glaux, but now it's GDI dependent. ideally it would have no OS dependencies. support for non powers of 2. ideally it would resize if the driver did not support non powers of two.
#include <windows.h>

GLuint BitmapToTexture(char* filename, COLORREF key/*= RGB(255, 0, 255)*/, unsigned char alpha/*=255*/, unsigned char key_alpha/*=0*/)
	GLuint texture = 0;							//the return value				
	BITMAP bmp;									//used only to get bmp dimensions
	HDC hDC = CreateCompatibleDC(NULL);			//choose DC like the desktop
	HBITMAP hBitmap = (HBITMAP)LoadImage(NULL,	//load the bitmap
										 0, 0, 

	if(hBitmap == NULL)							//bitmap failed to load
		return 0;
	//get bitmap dimensions
	GetObject(hBitmap, sizeof(BITMAP), &bmp);

	//allocate memory for the bitmap
	COLORREF *data = new COLORREF[bmp.bmWidth * bmp.bmHeight];

	//put it into our device context for GetPixel calls
	SelectObject(hDC, hBitmap);
	for(int y = 0; y < bmp.bmHeight; y++)
		for(int x = 0; x < bmp.bmWidth; x++)
			data[x + (y*bmp.bmHeight)] = GetPixel(hDC, x, y);
			if(key != data[x + (y*bmp.bmHeight)])
				data[x + (y*bmp.bmHeight)] |= (alpha << 24);
				data[x + (y*bmp.bmHeight)] |= (key_alpha << 24);

	//get rid of some GDI stuff we used to convert to RGB buffer
	//finally generate a texture
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA4, bmp.bmWidth, bmp.bmHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
	delete data;
	return texture;

Share this post

Link to post
Share on other sites

I implemented a simple BMP loader (only grayscale or RGB and no compression) by my self only using fopen(), fread() and fclose(). If you are intrested I can send it to you but it depends on a little bit of declarations within my environment so you cant use it out of the box.

But why not using some other file format? I am always using PNG now. To load it I use the excellent libpng which is cross platform and virtually everywhere available.


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this