png-or-not
Version:
A lightweight utility to check whether a given file or buffer is a valid PNG image by verifying its signature bytes(magic number). Perfect for validating image uploads or streams before processing.
21 lines (17 loc) • 576 B
JavaScript
/**
* Checks whether a given Buffer is a valid PNG image.
* PNG signature (magic number): 89 50 4E 47 0D 0A 1A 0A
*
* @param {Buffer} buffer - The buffer to check.
* @returns {boolean} - True if it's a valid PNG, false otherwise.
*/
function isPng(buffer) {
if (!Buffer.isBuffer(buffer)) return false;
if (buffer.length < 8) return false;
const pngSignature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
for (let i = 0; i < 8; i++) {
if (buffer[i] !== pngSignature[i]) return false;
}
return true;
}
module.exports = isPng;