Skip to content

Instantly share code, notes, and snippets.

@brussell98
Created August 18, 2018 00:00
Show Gist options
  • Save brussell98/dcdf2f0caf8db7870e16796cb7ce7f96 to your computer and use it in GitHub Desktop.
Save brussell98/dcdf2f0caf8db7870e16796cb7ce7f96 to your computer and use it in GitHub Desktop.
Image Difference
const util = require('util');
const sharp = require('sharp');
const imageDiff = require('native-image-diff');
const sizeOf = require('buffer-image-size');
const jpeg = require('jpeg-js');
const fs = require('fs');
const read = util.promisify(fs.readFile);
const files = ['./original1.jpg', './original2.png', './original3.jpg', './original4.png', './alternate4.png'];
async function compare() {
for (let i = 0; i < files.length; i++) {
console.log('-------------------------------');
console.log(`Image #${i + 1}`);
console.time(`Image #${i + 1}`);
const toCompare = await sharp(await read(files[i]))
.resize(2000, 2000)
.max()
.withoutEnlargement()
.background({ r: 255, g: 255, b: 255, alpha: 1 })
.flatten()
.jpeg({ quality: 92 })
.toBuffer();
const { width, height } = sizeOf(toCompare);
for (let f = 1; f < 5; f++) {
const file = await read(`./saved${f}.jpg`);
const { width: fWidth, height: fHeight } = sizeOf(file);
if (height !== fHeight || width !== fWidth)
continue;
const data = imageDiff.diffImages({
image1: jpeg.decode(toCompare),
image2: jpeg.decode(file),
generateDiffImage: false
});
console.log(` Diff for saved #${f}: ${data.pixels.toLocaleString()}px, delta ${data.totalDelta.toLocaleString()}, ${(data.pixels / (width * height) * 100).toFixed(4)}%`);
}
console.timeEnd(`Image #${i + 1}`);
}
}
compare();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment