#ifndef TGA_INC_CPP
#define TGA_INC_CPP
#include <cstdio>
bool tgaSave(const char *filename, const unsigned char *data, int w, int h, int ch) {
if (!data || w <= 0 || h <= 0 || w > 0xffff || h > 0xffff || (ch != 3 && ch != 4)) {
printf("ERROR: cannot save image (bad image): %s\n", filename);
return false;
}
FILE *f = fopen(filename, "wb");
if (!f) {
printf("ERROR: cannot open file: %s\n", filename);
return false;
}
#pragma pack(push,1)
struct Header {
unsigned char idLength;
unsigned char colormapType;
unsigned char imageType;
unsigned char colormapIndex[2];
unsigned char colormapLength[2];
unsigned char colormapSize;
unsigned char xOrigin[2];
unsigned char yOrigin[2];
unsigned char width[2];
unsigned char height[2];
unsigned char pixelSize;
unsigned char attributes;
};
#pragma pack(pop)
Header header = {};
header.imageType = 2;
header.width[0] = w;
header.width[1] = w >> 8;
header.height[0] = h;
header.height[1] = h >> 8;
header.pixelSize = ch == 4 ? 32 : 24;
fwrite(&header, sizeof(header), 1, f);
int rowSize = w*ch;
const unsigned char *row = data + h*rowSize;
for(unsigned short r = h; r; --r, row -= rowSize) {
for(const unsigned char *c = row - rowSize; c < row; c += ch) {
fputc(c[2], f);
fputc(c[1], f);
fputc(c[0], f);
if (ch == 4) fputc(c[3], f);
}
}
fclose(f);
return true;
}
#endif