Code Snippets
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Home :: Programming :: Code Snippets :: Cpp :: Loading TGA image files

[ Loading TGA image files ]

Targa or TGA is like Windows bitmap files an image format that is uncompressed and saves the raw colour information. Its advantages are that it is very easy to handle and that it has support for an Alpha colour channel allowing transparency. I won't go into the details of the image format so if you want to know more about TGA, take a look at wotsit.org.

The TGA loading code will be made of two parts: first we will create a little struct that stores information about the TGA file and then the actual TGA loading function. Here's the struct:

struct STGA
                data = (unsigned char*)0;
                width = 0;
                height = 0;
                byteCount = 0;

	~STGA() { delete[] data; data = 0; }

	void destroy() { delete[] data; data = 0; }

        int width;
	int height;
        unsigned char byteCount;
        unsigned char* data;

The STGA-struct saves everything that is important for us. It holds the image data, the image width & height and the image colour depth. Using C++ destructors, it will clean up the imageData array holding the pixel information, but only when it has been used.

Here's the TGA loading function:

bool loadTGA(const char *filename, STGA& tgaFile)
	FILE *file;
	unsigned char type[4];
	unsigned char info[6];

        file = fopen(filename, "rb");

        if (!file)
		return false;

	fread (&type, sizeof (char), 3, file);
	fseek (file, 12, SEEK_SET);
	fread (&info, sizeof (char), 6, file);

	//image type either 2 (color) or 3 (greyscale)
	if (type[1] != 0 || (type[2] != 2 && type[2] != 3))
		return false;

	tgaFile.width = info[0] + info[1] * 256;
	tgaFile.height = info[2] + info[3] * 256;
	tgaFile.byteCount = info[4] / 8;

	if (tgaFile.byteCount != 3 && tgaFile.byteCount != 4) {
		return false;

	long imageSize = tgaFile.width * tgaFile.height
 * tgaFile.width * tgaFile.byteCount;

	//allocate memory for image data
	tgaFile.data = new unsigned char[imageSize];

	//read in image data
	fread(tgaFile.data, sizeof(unsigned char), imageSize, file);

	//close file

	return true;

That's it! This function will load the specified TGA file and store the necessary data in the STGA structure. Here's a little snippet how to use it:

STGA tgaFile;
if (loadTGA("data/image.tga", &tgaFile))
   //Do things...
   // ex. create OpenGL texture using tgaFile->imageData etc.
//tgaFile will clean up itself thanks to destructor

I think TGA are very easy to handle but if you have still questions or comments, take at look at the message board. Happy Coding!

 Last edited 2006-02-14 01:44:06 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0