Programming Tips - C++: is a buffer a PNG or JPEG?

Date: 2020jan14
Language: C/C++
Keywords: JPG

Q.  C++: is a buffer a PNG or JPEG?

A.  Check for its magic string at the start.

typedef std::vector<BYTE> BYTE_ARRAY; // Helper static bool hasMagic(const BYTE_ARRAY &ba, const BYTE magic[], const size_t magicLen) { if (ba.size() < magicLen) return false; for (int i = 0; i < (int)magicLen; i++ ) { if (ba[i] != magic[i]) return false; } return true; } bool isPng(const BYTE_ARRAY &ba) { const BYTE magic[] = { 0x89, 'P', 'N', 'G' }; const size_t magicLen = sizeof(magic) / sizeof(magic[0]); return hasMagic(ba, magic, magicLen); } bool isJpeg(const BYTE_ARRAY &ba) { const BYTE magic[] = { 0xff, 0xd8 }; const size_t magicLen = sizeof(magic) / sizeof(magic[0]); return hasMagic(ba, magic, magicLen); }