Skip to content

Instantly share code, notes, and snippets.

@shalvah
Created April 26, 2020 18:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shalvah/d71e89dce0c6091c8ba1bc8f7fcdeddd to your computer and use it in GitHub Desktop.
Save shalvah/d71e89dce0c6091c8ba1bc8f7fcdeddd to your computer and use it in GitHub Desktop.
var Jimp = require('jimp');
const fileName = process.argv[2];
const width = process.argv[3];
const height = process.argv[4];
Jimp.read(fileName)
.then(photo => {
let colours = {};
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const colour = photo.getPixelColor(x, y);
colours[colour.toString(16).padStart(8, '0')] = colours[colour] ? ++colours[colour] : 1;
}
}
let [mostFrequentColourHex, ] = Object.entries(colours)
.reduce(([mostFrequentColourThusFar, highestFrequencyThusFar], [colour, frequency]) => {
if (Math.max(frequency, highestFrequencyThusFar)) {
return [colour, frequency];
}
return [mostFrequentColourThusFar, highestFrequencyThusFar];
});
console.log(Jimp.intToRGBA(Number("0x" + mostFrequentColourHex)));
console.log(mostFrequentColourHex);
new Jimp(256, 256, mostFrequentColourHex, (err, imageWithDominantColour) => {
// Write an image file with the dominant colour
imageWithDominantColour.write('dominant.png');
});
})
.catch(err => {
console.error(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment