Programming Tips - C/C++: Get the dimensions of a JPEG image from its binary

Date: 2021jul21 Language: C/C++ Keywords: size, JPG Q. C/C++: Get the dimensions of a JPEG image from its binary A.
#include <vector> 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(data[off] == 0xff) { off++; } const int mrkr = data[off]; 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