Because of the RIFF-like format of a jpeg, the image dimensions are not always stored in a constant location. The following routine can be used to calculate the dimensions of an image given the jpeg file. This is a C routine but should compile fine with C++. Pass it a normal FILE pointer (from fopen) to the beginning of a jpeg file and two int pointers to be set with the image height and width. Returns 0 on failure, nonzero on success. Doesn't close the file in either case. This routine is as public domain as is legally allowed. Since it was vaguely derived from the Independent JPEG code samples, you may have to leave in that notice.
/* portions derived from IJG code */ #define readbyte(a,b) do if(((a)=getc((b))) == EOF) return 0; while (0) #define readword(a,b) do { int cc_=0,dd_=0; \ if((cc_=getc((b))) == EOF \ || (dd_=getc((b))) == EOF) return 0; \ (a) = (cc_<<8) + (dd_); \ } while(0) int scanhead (FILE * infile, int * image_width, int * image_height) { int marker=0; int dummy=0; if ( getc(infile) != 0xFF || getc(infile) != 0xD8 ) return 0; for (; ;) { int discarded_bytes=0; readbyte(marker,infile); while (marker != 0xFF) { discarded_bytes++; readbyte(marker,infile); } do readbyte(marker,infile); while (marker == 0xFF); if (discarded_bytes != 0) return 0; switch (marker) { case 0xC0: case 0xC1: case 0xC2: case 0xC3: case 0xC5: case 0xC6: case 0xC7: case 0xC9: case 0xCA: case 0xCB: case 0xCD: case 0xCE: case 0xCF: { readword(dummy,infile); /* usual parameter length count */ readbyte(dummy,infile); readword((*image_height),infile); readword((*image_width),infile); readbyte(dummy,infile); return 1; break; } case 0xDA: case 0xD9: return 0; default: { int length; readword(length,infile); if (length < 2) return 0; length -= 2; while (length > 0) { readbyte(dummy, infile); length--; } } break; } } } Keywords: C++, C, routine, function, determine, calculate, jpeg, jpg, .jpg, .JPG, JPEG, file, image, width, height, jpegsize, graphics, file format, header, read, size |