diff --git a/src/image.c b/src/image.c index 284974c..e98f658 100644 --- a/src/image.c +++ b/src/image.c @@ -37,21 +37,36 @@ typedef enum { static twin_image_format_t image_type_from_name(const char *path) { twin_image_format_t type = IMAGE_TYPE_unknown; - const char *extname = strrchr(path, '.'); - if (!extname) + FILE *file = fopen(path, "rb"); + + if (!file) { + perror("File opening failed"); + return IMAGE_TYPE_unknown; + } + + unsigned char header[8]; + size_t bytesRead = fread(header, 1, sizeof(header), file); + fclose(file); + + if (bytesRead < 8) { return IMAGE_TYPE_unknown; + } + #if LOADER_HAS(PNG) - else if (!strcasecmp(extname, ".png")) { + if (header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && + header[3] == 0x47 && header[4] == 0x0D && header[5] == 0x0A && + header[6] == 0x1A && header[7] == 0x0A) { type = IMAGE_TYPE_png; } #endif + #if LOADER_HAS(JPEG) - else if (!strcasecmp(extname, ".jpg") || !strcasecmp(extname, ".jpeg")) { + else if (header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF) { type = IMAGE_TYPE_jpeg; } #endif - /* otherwise, unsupported format */ + /* otherwise, unsupported format */ return type; }