Date: 2021jul21
Update: 2026oct1
Language: C/C++
Keywords: size, JPG, width, height
Q. C/C++: Get the dimensions of a JPEG image from its binary
A. Here's a function for that:
typedef unsigned char BYTE;
typedef std::vector<BYTE> BYTE_ARRAY;
bool GetJpegDim(const BYTE_ARRAY &data, int &width, int &height) {
width = height = -1;
int off = 0;
while (off < (int)data.size()) {
while (off < (int)data.size()) {
if (data[off] != 0xff) break;
off++;
}
const int mrkr = data[off++];
if (mrkr == 0xd8) continue; // SOI
if (mrkr == 0xd9) break; // EOI
if (0xd0 <= mrkr && mrkr <= 0xd7) continue;
if (mrkr == 0x01) continue; // TEM
const int len = (data[off]<<8) | data[off+1]; off += 2;
if (mrkr == 0xc0) {
const int bpc = data[off]; // Precision (bits per channel)
height = (data[off+1]<<8) | data[off+2];
width = (data[off+3]<<8) | data[off+4];
const int cps = data[off+5]; // Number of color components
return true;
}
off += len - 2;
}
return false;
}
Based on code in other languages on
https://stackoverflow.com/questions/2517854/getting-image-size-of-jpeg-from-its-binary
Full Example Use:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
// (Place the above typedef's and function GetJpegDim() here)
BYTE_ARRAY readAll(FILE *f) {
BYTE_ARRAY v;
BYTE buf[2];
for (;;) {
if (fread(buf, 1, 1, f) == 0) break;
v.push_back(buf[0]);
}
return v;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: jpegsize <filename>\n");
exit(1);
}
const char *filename = argv[1];
{
FILE *f;
if ((f = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
auto content = readAll(f);
if (content.size() <= 0) {
fprintf(stderr, "Could not read file %s\n", filename);
exit(1);
}
printf("Read %d bytes\n", content.size());
int width, height;
if (!GetJpegDim(content, width, height)) {
fprintf(stderr, "Could not find the size of JPEG %s\n", filename);
exit(1);
}
printf("Image %s is %d x %d\n", filename, width, height);
fflush(stdout);
}
{
char buf[1000];
printf("Size from ImageMagick...\n");
snprintf(buf, sizeof(buf), "identify %s", filename);
system(buf);
}
}
Running:
./jpegsize /usr/share/cups/www/images/smiley.jpg
Output:
Read 14120 bytes
Image /usr/share/cups/www/images/smiley.jpg is 445 x 570
Size from ImageMagick...
/usr/share/cups/www/images/smiley.jpg JPEG 445x570 ...