#include <stdio.h> bail(unsigned char a, unsigned char b) { if (a != b) { printf("Invalid JFIF: %x != %x\n",a,b); exit(-1); } } int isin(unsigned char a, const unsigned char* parameterless) { int i; int found=0; for (i=0;i<parameterless[0] && !found;i++) { if (a == parameterless[i+1]) found = 1; } return found; } int readword(FILE* foo) { unsigned char b; int word=0; fread(&b,1,1,foo); word = 256 * b; fread(&b,1,1,foo); word += b; return word; } main(int argc, char** argv) { int i, len, width=-1, height=-1; FILE *foo; unsigned char b; static const unsigned char parameterless[]={8,0x01,0xd1,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7}; static const unsigned char sig[]={2,0xff,0xd8}; if (argc != 2) { printf("sizeof takes a single argument -- a jpeg filename\n"); exit(0); } printf("attempting to open: %s\n",argv[1]); foo = fopen(argv[1],"rb"); if (!foo) { printf("ERROR OPENING FILE\n"); } for (i=0;i<sig[0];i++) { fread(&b,1,1,foo); printf("%x\n",b); bail(b,sig[i+1]); } while (fread(&b,1,1,foo)) { while (b == 0xff) { fread(&b,1,1,foo); if (b == 0xc0 || b == 0xc1) { fseek(foo,3,SEEK_CUR); height = readword(foo); width = readword(foo); } else { if (!isin(b,parameterless)) { len = readword(foo); fseek(foo,len-2,SEEK_CUR); fread(&b,1,1,foo); } else { b = 0xff; // keep going :) } } } } printf("width: %d, height: %d\n",width,height); }
All that to get the width/height of a jpeg. I spent close to four hours trying to figure it out on my own, from the JFIF specs (I don't know if this handles the SPIFF spec, but I don't seem to have any JPEGs in SPIFF). And that was after an hour or two just _digging_ for the JFIF spec (not realizing I wanted JFIF as opposed to JPEG, for instance...)