Reading bitmaps

Hello, I'm trying to read bitmaps to use them as textures in OpenGL, but for some reason, the file isn't read correctly into the stream. Here's my code:


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#define BM 0x424D

int LoadBMP(const wchar_t * path, GLuint & texture)
{
	std::pair<UINT8*,UINT8*> bufferData(nullptr, nullptr);
	UINT8* pixels = nullptr;

	bufferData.first  = new UINT8[sizeof(BITMAPFILEHEADER)];
	bufferData.second = new UINT8[sizeof(BITMAPINFOHEADER)];

	BITMAPFILEHEADER * bmpHeader = nullptr;
	BITMAPINFOHEADER * bmpInfo = nullptr;

	std::ifstream image;

	try 
	{
		image.open(path, std::ios::in | std::ios::binary);
	}
	catch (std::ifstream::failure e)
	{
		std::wcerr << L"\nError opening file";
		return -1;
	}

	image.read((char*)bufferData.first, sizeof(BITMAPFILEHEADER));
	image.read((char*)bufferData.second,sizeof(BITMAPINFOHEADER));

	bmpHeader = (BITMAPFILEHEADER*) bufferData.first;
	bmpInfo   = (BITMAPINFOHEADER*) bufferData.second;

	if (bmpHeader->bfType != BM);
	{
	   std::wcerr << L"\nError, invalid file format";
		return -1;
	}

	pixels = new UINT8[bmpInfo->biSizeImage];

	image.seekg(bmpHeader->bfOffBits);
	image.read((char*)pixels, bmpInfo->biSizeImage);

	for (_int64 i = 0; i < bmpInfo->biSizeImage; i += 3)
	{
		pixels[i]       ^= pixels[i + 2];
		pixels[i + 2] ^= pixels[i];
		pixels[i]       ^= pixels[i + 2];
	};

	GLuint w = bmpInfo->biWidth;
	GLuint h = bmpInfo->biHeight;

	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);

	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, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
	glBindTexture(GL_TEXTURE_2D, NULL);

	delete[] pixels;
	delete[] bufferData.first;
	delete[] bufferData.second;

	return 0;
}


When I try to read the stream buffer into another file, I get a scrambled image. What's the problem? Thanks in advance!
Last edited on
I thought bitmaps were RGBA formatted. Or maybe sometimes they are, I can't recall -- I always just used raw (pure rgb format) binary files for textures.

closed account (E0p9LyTq)
http://stackoverflow.com/questions/20595340/loading-a-tga-bmp-file-in-c-opengl
Topic archived. No new replies allowed.