Search code examples
imagefiletga

.tga Image: Value that should be represented by a word is only correct if I read the first half word


I have the following problem: I am trying to read the header of a tga file and so I went on Wikipedia to get the structure of a tga file: There it says that the image width and height are stored as one word or 2 bytes of data in the header. But then I looked at the hex code of a tga file header (the first 18 bytes):

00 00 02 00 00 00 00 00 00 00 00 00 20 00 20 00 20 08

Here the 3rd and 2nd last words are the width and height. So according to this my tga file should be 8.192px wide and 8.192px high (0x2000) but in reality the image is only 32px wide and 32px high (0x20 - first byte).

Do you have an explanation for this?


Solution

  • Let's make an image 513px wide and 32px tall with ImageMagick in Terminal and hex-dump it:

    magick -size 513x32 xc:red tga: | xxd -c 16
    

    And we get this:

    enter image description here

    According to your Wikipedia link. the fields are as follows:

    • red - Field 1 - ID Length
    • green - Field 2 - colormap type
    • blue - Field 3 - image type
    • cyan - Field 4 - colormap specification
    • magenta - x,y origin - [0,0]
    • yellow - width
    • white - height

    So, let's look at the width. I made it 513 px, which is 2 x 256 + 1. So, hopefully you can see that the Targa specification is little-endian, where the least significant byte comes first, and the more significant byte comes second. That means 0102 is 1 small, insignificant byte and 2*256 big, fat bytes. Likewise, the 20000 for the height means 2 lots of 16 smallish bytes and zero lots of big, fat bytes.

    TLDR: Targa format is little-endian. The least significant bytes come first then the more significant bigger bytes.