Skip to content

Instantly share code, notes, and snippets.

@vandycknick
Created January 6, 2017 13:04
Show Gist options
  • Save vandycknick/0184de12681c41481042cdd88e387f78 to your computer and use it in GitHub Desktop.
Save vandycknick/0184de12681c41481042cdd88e387f78 to your computer and use it in GitHub Desktop.
var fs = require('fs');
fs.readFile('./map-pin-default.png', function(err, buffer) {
if(err) {
console.log(err);
}else {
var list = parsePng(buffer);
var tEXt = list[1];
var iTXt = list[2];
console.log(list);
console.log(tEXt.data.toString());
console.log(iTXt.data.toString('UTF8'));
}
});
function parsePng(buffer) {
var list = [];
var position = 8;
var length = buffer.length;
if(isPng(buffer)) {
while(position < length) {
var size = buffer.readUIntBE(position, 4);
var eofChunk = position + size + 12;
var chunkBuffer = buffer.slice(position, eofChunk);
var chunk = {};
chunk.size = size;
chunk.type = chunkBuffer.toString('utf8', 4, 8);
chunk.data = chunkBuffer.slice(8, 8 + size);
chunk.crc = chunkBuffer.readUIntBE(8 + size, 4);
list.push(chunk);
position = eofChunk;
}
}
return list;
}
function isPng(buffer) {
if (
buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47 &&
buffer[4] === 0x0d && buffer[5] === 0x0a && buffer[6] === 0x1a && buffer[7] === 0x0a
) {
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment