Skip to content

Commit

Permalink
Using header of image to determine supported format
Browse files Browse the repository at this point in the history
  • Loading branch information
Damien-Chen committed Aug 22, 2024
1 parent fd3e451 commit b9400d6
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/image.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down

0 comments on commit b9400d6

Please sign in to comment.