#include "img.ldr.tga.inc.c"
#ifdef PNG_LIBPNG_VER_STRING
#include "img.ldr.png.inc.c"
#endif
typedef int (*ImageLoadFunc)(const char *path, int *outWidth, int *outHeight, unsigned char **pixels);
typedef int (*ImageSaveFunc)(const char *path, int width, int height, const unsigned char *pixels);
int checkExt(const char *path, const char *ext) {
int lp = strlen(path);
int le = strlen(ext);
if (lp <= le) return FALSE;
if (path[lp-le-1] != '.') return FALSE;
for(const char *a = path+lp-le, *b = ext; *b; ++a, ++b)
if (tolower(*a) != tolower(*b)) return FALSE;
return TRUE;
}
int imageLoadAuto(const char *path, int *outWidth, int *outHeight, unsigned char **pixels) {
struct {
const char *ext;
ImageLoadFunc func;
} formats[] = {
{ "tga", &imageLoadTga },
#if defined(HELI_HELIANTUS_H)
{ "png", &imageLoad },
#elif defined(PNG_LIBPNG_VER_STRING)
{ "png", &imageLoadPng },
#endif
};
int cnt = sizeof(formats)/sizeof(*formats);
for(int i = 0; i < cnt; ++i)
if (checkExt(path, formats[i].ext))
return formats[i].func(path, outWidth, outHeight, pixels);
fprintf(stderr, "Cannot load this image format (supported formats:");
for(int i = 0; i < cnt; ++i)
fprintf(stderr, " %s", formats[i].ext);
fprintf(stderr, "): %s\n", path);
fflush(stderr);
return FALSE;
}
int imageSaveAuto(const char *path, int width, int height, const unsigned char *pixels) {
struct {
const char *ext;
ImageSaveFunc func;
} formats[] = {
{ "tga", &imageSaveTga },
#if defined(HELI_HELIANTUS_H)
{ "png", (ImageSaveFunc)&imageSave },
#elif defined(PNG_LIBPNG_VER_STRING)
{ "png", &imageSavePng },
#endif
};
int cnt = sizeof(formats)/sizeof(*formats);
for(int i = 0; i < cnt; ++i)
if (checkExt(path, formats[i].ext))
return formats[i].func(path, width, height, pixels);
fprintf(stderr, "Cannot save this image format (supported formats:");
for(int i = 0; i < cnt; ++i)
fprintf(stderr, " %s", formats[i].ext);
fprintf(stderr, "): %s\n", path);
fflush(stderr);
return FALSE;
}
int imgLoad(Img *img, const char *path) {
imgDestroy(img);
int w, h;
unsigned char *data;
if (!imageLoadAuto(path, &w, &h, &data))
{ free(data); return FALSE; }
imgFromInt(img, w, h, data);
free(data);
return TRUE;
}
int imgSave(Img *img, const char *path) {
unsigned char *data = imgToInt(img);
if (!imageSaveAuto(path, img->w, img->h, data))
{ free(data); return FALSE; }
free(data);
return TRUE;
}