Date: 2019jan21
Update: 2026sep28
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
Full Example Use:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
// (Include the above function here)
std::vector<std::byte> readN(FILE *f, const int n) {
std::vector<std::byte> v;
char buf[2];
for (int i = 0; i < n; i++) {
if (fread(buf, 1, 1, f) == 0) {
perror("fread");
exit(1);
}
v.push_back((std::byte)buf[0]);
}
return v;
}
int main() {
FILE *f = fopen("example.png", "rb");
if (!f) {
perror("fopen");
exit(1);
}
auto bytes = readN(f, 10);
if (bytes.size() != 10) {
fprintf(stderr, "Could not read 10 bytes\n");
exit(1);
}
if (isPng(bytes)) {
printf("This file IS a PNG\n");
}
else {
printf("This file is NOT a PNG\n");
}
}
Output:
This file IS a PNG