Skip to content

Instantly share code, notes, and snippets.

@magalhini
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magalhini/80ef9ef130d904304d3e to your computer and use it in GitHub Desktop.
Save magalhini/80ef9ef130d904304d3e to your computer and use it in GitHub Desktop.
node.js Image Comparison with GIF output
/* Takes two images and compares them.
* If they're different, a GIF with the differences will be created.
*
* @requires ImageMagick to be installed to generate the GIF :(
* Install it via Homebrew: brew install imagemagick
*
* @usage: node screenshot.js file1.jpg file2.jpg
*/
var pngparse = require('pngparse');
var exec = require('child_process').exec;
var args = process.argv;
var image1,
image2;
function compare() {
image1 = args[2];
image2 = args[3];
if (!image1 || !image2) {
throw new Error('You need 2 files.');
}
parseImage(image1, function (img1) {
parseImage(image2, function (img2) {
compareFiles(img1, img2)
});
});
}
function parseImage(filePath, callback) {
pngparse.parseFile(filePath, function (err, res) {
if (err) {
throw new Error('Error parsing image1', err);
}
if (callback) {
callback(res);
}
return res;
});
}
function compareFiles(first, second) {
var i = 0,
len = first.data.length;
for (i; i < len; i += 4) {
if (first.data[i] !== second.data[i] ||
first.data[i + 1] !== second.data[i + 1] ||
first.data[i + 2] !== second.data[i + 2]) {
return createDiffGif();
}
}
console.log('No difference between files');
return false;
}
function createDiffGif() {
console.log('Files are different! Creating GIF...');
exec('convert -delay 50 -loop 0 ' + image1 + ' ' + image2 + ' difference.gif');
}
// For CLI only with this
module.exports = compare();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment