summaryrefslogtreecommitdiff
path: root/src/tga.c
blob: 95a82d6f26402c6eab40e2553758d6e59126f869 (plain)
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
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void CreateTGA( char *filename, short width, short height, void *image ) {
    
    // create file pointer to write to
    FILE *tga = NULL;

    // write filename from func arg to buffer
    char buffer[256];
    if( filename ) {
        strncpy( buffer, filename, sizeof(buffer) );
    }
    // if no filename is provided, set default
    else {
        strcpy( buffer, "img.tga" );
    }

    // open the named file for binary writing
    tga = fopen( buffer, "wb" );

    // set 'id length' field of tga header
    fputc( 0, tga );
    

    // set 'color map type' field of tga header
    fputc( 1, tga ); // color map present

    // set 'image type' field of tga header
    fputc( 1, tga ); // uncompressed color mapped image

    // set 'color map specification' field of tga header
    fputc( 0, tga ); fputc( 0, tga ); // 2 byte 'first entry index' subfield, index 0
    fputc( 2, tga ); fputc( 0, tga ); // 2 byte 'color map length' subfield, 2 entries
    fputc( 24, tga ); // 'color map entry size' subfield, 24-bit color

    // set 'image specification' field of tga header
    fputc( 0, tga ); fputc( 0, tga ); // 2 byte 'x-origin' subfield, origin 0
    fputc( 0, tga ); fputc( 0, tga ); // 2 byte 'y-origin' subfield, origin 0
    fputc( width & 0xff, tga ); fputc( width >> 8, tga ); // 2 byte 'width' subfield, set by function argument 'w'
    fputc( height & 0xff, tga ); fputc( height >> 8, tga ); // 2 byte 'height' subfield, set by function argument 'h'
    fputc( 8, tga ); // 'pixel depth' subfield, 8 bits per pixel
    fputc( 0x20, tga ); // 'image descriptor' subfield, bit 5 set, indicating top-to-bottom, left-to-right order
    
    // set 'image and color map data' field
    fputc( 0xff, tga ); fputc( 0xff, tga ); fputc( 0xff, tga ); // set first color map entry, 0xffffff
    fputc( 0x00, tga ); fputc( 0x00, tga ); fputc( 0x00, tga ); // set second color map entry, 0x000000

    // write image data
    fwrite( image, 1, (width * height), tga );

    fclose( tga );
}