Firstly I want to say I tried many times to find the answer by using google search, and I found many results but I did not understand, because I don't know the idea of reading a binary file, and convert the value that Obtained to readable value.
What I tried doing it.
unsigned char fbuff[16];
FILE *file;
file = fopen("C:\\loser.jpg", "rb");
if(file != NULL){
fseek(file, 0, SEEK_SET);
fread(fbuff, 1, 16, file);
printf("%d\n", fbuff[1]);
fclose(file);
}else{
printf("File does not exists.");
}
I want a simple explanation with example shows, how to get width/height of jpeg file from its header, and then convert that value to readable value.
Unfortunately, it doesn't seem to be simple for JPEG. You should look at the source to the
jhead
command line tool. It provides this information. When going through the source, you will see the functionReadJpegSections
. This function scans through all the segments contained within the JPEG file to extract the desired information. The image width and height is obtained when processing the frames that have anSOFn
marker.I see the source is in the public domain, so I'll show the snippet that gets the image info:
From the source code, it is clear to me there is no single "header" with this information. You have to scan through the JPEG file, parsing each segment, until you find the segment with the information in it that you want. This is described in the wikipedia article:
A JPEG file consists of a sequence of segments:
Each segment begins with a 2-byte marker. The first byte is
0xFF
, the second byte determines the type of the segment. This is followed by an encoding of the length of the segment. Within the segment is data specific to that segment type.The image width and height is found in a segment of type
SOFn
, or "Start of frame [n]", where "n" is some number that means something special to a JPEG decoder. It should be good enough to look only for aSOF0
, and its byte designation is0xC0
. Once you find this frame, you can decode it to find the image height and width.So the structure of a program to do what you want would look like:
This is essentially the structure found in Michael Petrov's
get_jpeg_size()
implementation.then you have to find hight and width marker of jpeg that is [ffc0].
after finding ffc0 in binary formate, the the four,five bytes are hight and six and seven bytes are width.
Image dimensions in JPEG files can be found as follows:
1) Look for FF C0
2) At offsets +4 and +6 after this location are height and width (words), resp/ly.
In most cases, the absolute offsets of height and width are A3 and A5, resp/ly.
Here's some simple code I wrote which seems to work reliably.
the question is old and the other answers are correct but their format is not the easiest one. I just use
getc
to quickly get the dimensions, while skipping irrelevant markers (it also supports Progressive JPEGs):