OpenGL BMP Loader Help Please.

So, I have a texture loader that works decently well, however, it only loads BMP's that have a bit-depth of 24! I don't know why this is, but if you see any problems in my code, please tell me. Thank you for your time!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
GLuint LoadTexture(const char * pic, int width, int height)
{
	GLuint Texture;
	BYTE * data;
	FILE * picfile;
	FILE * in;

	picfile = fopen(pic, "rb");
	if (picfile == NULL)
		return 0;

	data = (BYTE *)malloc(width * height * 3);

	BITMAPFILEHEADER MyHeaderFile;
	fread(&MyHeaderFile, sizeof(BITMAPFILEHEADER), 1, picfile);
	if (MyHeaderFile.bfType != 19778)
		return 0;

	BITMAPINFOHEADER MyHeaderInfo;
	fread(&MyHeaderInfo, sizeof(BITMAPINFOHEADER), 1, picfile);

	fseek(picfile, MyHeaderFile.bfOffBits, SEEK_SET);
	fread(data, width * height, 3, picfile);
	fclose(picfile);
	
        glGenTextures(1, &Texture);
	glBindTexture(GL_TEXTURE_2D,  Texture);

	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);

	free(data);
	return Texture;
}



- Kyle
Last edited on
It's got quite a few problems.

-) It only reads a bit depth of 24 because of line 23 (note how you're reading 3 bytes per pixel. 3 bytes = 24 bits)

-) You're ignoring the pitch (byte size of one row) and assuming the width is the pitch. This is incorrect. The pitch is actually rounded up to the nearest DWORD boundary (4-byte boundary). So if you have a width of 9 pixels, with 3 bytes per pixel.... the pitch is actually 28, not 27 like you're assuming. This might cause your textures to be skewed.

-) Bitmaps are [usually] stored upside-down (bottom row first), whereas OpenGL takes textures top row first. Your textures are going to be loaded upside-down.

-) OpenGL requires texture sizes to be a power of 2 (ie, 256 and 512 are valid widths, but 300 is not). Your loaded textures here will look like garbage on many OpenGL implementations unless all the image files you're loading are a power of 2 size.

-) You're not reading the bitmap dimentions (or bit depth) from the file, you're just assuming the width/height match what is passed to the function and that the bit depth is always 24-bit.

-) There's probably more... but you get the idea...


I really recommend using a library to load image files to GL textures. There are tons available (SOIL is a popular one).
Last edited on
Thank you so much! This fixes TONS of my problems! Also, it has made me realize some other problems that I didn't notice. Thank you.

- Kyle
Topic archived. No new replies allowed.