Created
May 30, 2018 23:40
-
-
Save bultas/f52b2112fcec21b28e4af9e349f39d6b to your computer and use it in GitHub Desktop.
Compare images - perceptual diffing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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