Creating TGA Image files

Introduction

TGA or TARGA format is a format for describing bitmap images, it is
capable of representing bitmaps ranging from black and white,
indexed colour, and RGB
colour, the format also supports various compression methods.
This note describes the minimal requirements for creating a TGA file for
a 24 bit RGB uncompressed colour image, this covers most applications
where a developer might want to create an image for another package
which reads TGA files.
A more complete description of the format is given after this
special case and the complete specification is supplied at the end.

Mimimal requirements for writing a TGA file of a 24 or 32 bit image

A TGA file consists of 2 main parts, a header followed by the colour pixel
information. The minimal header consists of the size of the bitmap
and the amount of colour information. In cases where an integer is
written to a file the information is stored with the low order byte
followed by the high order byte, ie: little endian.

To determine the possible use of the other fields see the full format
description below. TGA can support a fourth alpha channel, just
specify 32 instead of 24 for the depth, the alpha channel comes
after the red byte.

In the special case of 24 bit colour described here
the image data consists of 3 bytes per pixel, for the red, green, and
blue component in the normal colour cube space.
The image pixel data should follow for width * height pixels,
a single pixel might be written as

More complete description

The header (18 bytes) might be defined as follows for C/C++.
You should be careful with this since it has byte values which some
compilers will align to natural boundaries. This is checked by printing
out the sizeof(HEADER), if it greater than 18 then byte alignment is
taking effect and a fread() using the struct below will not give the right
results. In that case you either need to read your compiler manual and
turn off boundary alignment, of read the components one at a time, sigh!

The bitsperpixel specifies the size of each colour value. When
24 or 32 the normal conventions apply. For 16 bits each colour component
is stored as 5 bits and the remaining bit is a binary alpha value.
The colour components are converted into single byte components by
simply shifting each component up by 3 bits (multiply by 8).

Source code

Here is some simple source code
tgatest.c
that reads a compressed or uncompressed
TGA file of either 16, 24, or 32 bit colour and writes an uncompressed
version. The primary purpose is to illustrate how the RLE compression
works and the implementation of 16 bit extraction.