--- /dev/null
+#pragma pack(push, 1)
+struct tga_header
+{
+ char idlength;
+ char colourmaptype;
+ char datatypecode;
+ short int colourmaporigin;
+ short int colourmaplength;
+ char colourmapdepth;
+ short int x_origin;
+ short int y_origin;
+ short width;
+ short height;
+ char bitsperpixel;
+ char imagedescriptor;
+};
+#pragma pack(pop)
+
+// Requires RGBA data. Can write grayscale (comp=1), RGB (comp=3) or RGBA (comp=4)
+int csr_tga_write( const char *path, u32 width, u32 height, int comp, u8 *rgba )
+{
+ FILE *fp = fopen( path, "wb" );
+
+ if( fp )
+ {
+ struct tga_header header =
+ {
+ .datatypecode = 2,
+ .width = width,
+ .height = height,
+ .bitsperpixel = comp * 8,
+ .imagedescriptor = 0x20
+ };
+
+ fwrite( &header, sizeof( struct tga_header ), 1, fp );
+
+ for( u32 i = 0; i < width * height; i ++ )
+ {
+ u8 *colour = rgba + i*4;
+ u8 flipped[4];
+
+ if( comp >= 3 )
+ {
+ flipped[0] = colour[2];
+ flipped[1] = colour[1];
+ flipped[2] = colour[0];
+ flipped[3] = colour[3];
+
+ colour = flipped;
+ }
+
+ fwrite( colour, 1, comp, fp );
+ }
+
+ fclose( fp );
+ return 1;
+ }
+ else
+ {
+ return 0;
+ }
+}