Skip to content

Instantly share code, notes, and snippets.

@bultas
Created May 30, 2018 23:40
Show Gist options
  • Save bultas/f52b2112fcec21b28e4af9e349f39d6b to your computer and use it in GitHub Desktop.
Save bultas/f52b2112fcec21b28e4af9e349f39d6b to your computer and use it in GitHub Desktop.
Compare images - perceptual diffing
import R from 'ramda';
import fs from 'fs';
import { PNG } from 'pngjs';
import pixelmatch from 'pixelmatch';
export const getImages = imagesPaths => {
return new Promise(resolve => {
let filesRead = 0;
let images = [];
R.forEach(imagePath => {
const img = fs
.createReadStream(imagePath)
.pipe(new PNG())
.on('parsed', doneReading);
function doneReading() {
filesRead += 1;
images = [...images, img];
if (filesRead < imagesPaths.length) return;
resolve(images);
}
}, imagesPaths);
});
};
export const compareImages = R.curry(async (diffPath, imagePath, imagePath2) => {
const images = await getImages([imagePath, imagePath2]);
const png1 = images[0];
const png2 = images[1];
const diff = new PNG({ width: png1.width, height: png1.height });
const diffCount = pixelmatch(png1.data, png2.data, diff.data, png1.width, png1.height, {
threshold: 0.1
});
if (diffCount > 0) {
diffPath && diff.pack().pipe(fs.createWriteStream(diffPath));
throw Error('Images are not equal');
}
return true;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment