Code:
// structure for loading TGA bitmaps
typedef struct
{
int imageWidth;
int imageHeight;
unsigned int imageTypeCode;
unsigned int bitCount;
unsigned char* imageData;
} STGA;
// the TGA bitmap loader
bool loadTGA(char *filename, STGA tgaFile)
{
FILE *file;
unsigned char badChar;
short int badInt;
long imageSize;
int colorMode;
file = fopen(filename, "rb");
if (!file)
return false;
fread(&badChar, sizeof(unsigned char), 1, file);
fread(&badChar, sizeof(unsigned char), 1, file);
fread(&tgaFile.imageTypeCode, sizeof(unsigned char), 1, file);
//image type either 2 (color) or 3 (greyscale)
/* if ((tgaFile.imageTypeCode != 2) && (tgaFile.imageTypeCode != 3))
{
fclose(file);
return false;
} */
//13 bytes of useless data
fread(&badInt, sizeof(short int), 1, file);
fread(&badInt, sizeof(short int), 1, file);
fread(&badChar, sizeof(unsigned char), 1, file);
fread(&badInt, sizeof(short int), 1, file);
fread(&badInt, sizeof(short int), 1, file);
int imagewidth = 0;
int imageheight = 0;
//image dimensions
fread(&tgaFile.imageWidth, sizeof(short int), 1, file);
fread(&tgaFile.imageHeight, sizeof(short int), 1, file);
if (tgaFile.imageWidth != 256)
printf("%a x %b\n", imagewidth, imageheight);
//image bit depth
fread(&tgaFile.bitCount, sizeof(unsigned char), 1, file);
// print the depth count
// printf("%a\n", tgaFile.bitCount);
//1 byte of garbage data
fread(&badChar, sizeof(unsigned char), 1, file);
//colorMode -> 3 = BGR, 4 = BGRA
colorMode = tgaFile.bitCount / 8;
imageSize = tgaFile.imageWidth * tgaFile.imageHeight * colorMode;
//allocate memory for image data
tgaFile.imageData = (unsigned char*) malloc (imageSize);
//read in image data
fread(tgaFile.imageData, sizeof(unsigned char), imageSize, file);
int i; // looping variable
//change BGR to RGB (especially for OpenGL later on)
for (i = 0; i < imageSize; i += colorMode)
{
//swap blue and red colour value
tgaFile.imageData[i] ^= tgaFile.imageData[i+2] ^=
tgaFile.imageData[i] ^= tgaFile.imageData[i+2];
}
//close file
fclose(file);
return true;
}