Programming Tips - C/C++: Check if a vector of bytes is a PNG image

Date: 2019jan21 Update: 2025sep4 Language: C/C++ Q. C/C++: Check if a vector of bytes is a PNG image A. Check it starts with the magic string "0x89 P N G"
bool isPng(const std::vector<std::byte> &ba) { const std::byte magic[] = { 0x89, 'P', 'N', 'G' }; const int magicLen = sizeof(magic) / sizeof(magic[0]); if (ba.size() < magicLen) return false; for (int i = 0; i < magicLen; i++ ) { if (ba[i] != magic[i]) return false; } return true; }
Actually the full magic number is 8 bytes but testing for these 4 is definitely sufficient. https://en.wikipedia.org/wiki/PNG