Skip to content

Instantly share code, notes, and snippets.

@iamhosseindhv
Last active July 21, 2018 21:55
Show Gist options
  • Select an option

  • Save iamhosseindhv/eac8f932df3e4e60c577d4cda0aeff09 to your computer and use it in GitHub Desktop.

Select an option

Save iamhosseindhv/eac8f932df3e4e60c577d4cda0aeff09 to your computer and use it in GitHub Desktop.
Coverts a .txt file containing binary values to a .png image
/**
* Coverts a .txt file containing
* binary values to a .png image
*
* Usage: node binary2png.js binary.txt
*/
let fs = require('fs');
let PNG = require('pngjs').PNG;
const inputFile = process.argv.slice(2)[0];
getMatrix(inputFile).then(matrix => {
const dimention = Math.floor(Math.sqrt(matrix.length));
let png = new PNG({
width: dimention,
height: dimention,
filterType: -1
});
let j = 0;
for (var y = 0; y < png.height; y++) {
for (var x = 0; x < png.width; x++) {
var idx = (png.width * y + x) << 2;
//rgb
png.data[idx] = matrix[j][0];
png.data[idx + 1] = matrix[j][1];
png.data[idx + 2] = matrix[j][2];
//alpha
png.data[idx + 3] = 255;
j++;
}
}
png.pack().pipe(fs.createWriteStream('myCode.png'))
});
const getMatrix = inputFile => {
return new Promise((resolve, reject) => {
fs.readFile(inputFile, 'utf8', (err, data) => {
if (err) reject(err);
const matrix = getRgbMatrix(data);
resolve(matrix);
});
});
};
const getRgbMatrix = (stringOfBinary) => {
const data = stringOfBinary.split(' ');
let matrix = [], rgb = [];
for (let i = 0; i < data.length; i++) {
let px = parseInt(data[i], 2);
if (px > 127) px -= 256;
rgb.push(px);
if ((i + 1) % 3 === 0) {
matrix.push(rgb);
rgb = [];
}
}
return matrix;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment