TGA-Loader für Qt
Verfasst: 2. Juni 2010 17:17
Qt kann einige Formate importieren, aber kein TGA.
Deshalb hier eine kleine Funktion, die genau das macht. Jedoch unterstützt sie keine RLE-Kompression.
Ich hab den Original Code für OpenGL von einem Freund bekommen und für Qt umgeschrieben. Ich hoffe, ihr könnt ihn brauchen!
Verbesserungsvorschläge sind natürlich herzlich willkommen!
Deshalb hier eine kleine Funktion, die genau das macht. Jedoch unterstützt sie keine RLE-Kompression.
Code: Alles auswählen
QPixmap LoadTGAImage(const char *filename)
{
unsigned char hdr[18];
unsigned char file_id[256 + 1];
QImage r;
int file;
/* Open file */
file = open(filename, O_RDONLY);
if(file < 0)
{
printf("Error: Failed to open tga file '%s' for reading", filename);
return 0;
}
/* Read header */
if(read(file, hdr, 18) != 18 || read(file, file_id, hdr[0]) != hdr[0])
{
printf("Error: Unexpected EOF while reading header of '%s'", filename);
close(file);
return 0;
}
file_id[hdr[0]] = 0;
if(hdr[1] != 0 || (hdr[2] != 2 && hdr[2] != 3) || (hdr[16] != 8 && hdr[16] != 16 && hdr[16] != 24 && hdr[16] != 32))
{
printf("Error: File '%s' has invalid format", filename);
close(file);
return 0;
}
int width = *(short *)(hdr + 12);
int height = *(short *)(hdr + 14);
int components = hdr[16] / 8;
/* Read image data */
unsigned char *data = new unsigned char [width * height * components];
if(read(file, data, width * height * components) != width * height * components)
{
printf("Error: Unexpected EOF while reading image data of '%s'", filename);
close(file);
return 0;
}
/* Check for overlength! */
char dummy;
if(read(file, &dummy, 1) == 1)
printf("Warning: TGA file '%s' has overlength", filename);
close(file);
r = QImage(width, height, QImage::Format_RGB32);
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
r.setPixel(x, y, QColor(data[(x + y * width) * components + 2],
data[(x + y * width) * components + 1],
data[(x + y * width) * components + 0]).rgb());
delete data;
return QPixmap::fromImage(r);
}
Verbesserungsvorschläge sind natürlich herzlich willkommen!