Created
April 19, 2022 01:03
-
-
Save hyunbinseo/80579c81a363789c027facb7047249db to your computer and use it in GitHub Desktop.
Get dominant color from images in RGB or HEX
This file contains 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
// https://github.com/lokesh/color-thief | |
const ColorThief = require('colorthief'); | |
// Preferences | |
const directory = './images'; | |
const extension = 'jpg'; | |
const filenames = [ | |
'loon-yyy-riven', | |
'dining-agreed-gumball', | |
'cowan-logs-bagged', | |
]; | |
// Utility | |
const rgbToHex = (r, g, b) => { | |
const values = [r, g, b].map((value) => { | |
const hex = value.toString(16); | |
return hex.length === 1 ? `0${hex}` : hex; | |
}); | |
return `#${values.join('')}`; | |
}; | |
// Conversion | |
const promises = []; | |
filenames.forEach((filename) => { | |
const promise = ColorThief | |
// When run in Node, this argument expects a path to the image. | |
// https://lokeshdhakar.com/projects/color-thief/#api | |
.getColor(`${directory}/${filename}.${extension}`) | |
// Returns RGB value in [Number, Number, Number] form | |
// https://lokeshdhakar.com/projects/color-thief/#api | |
.then(([r, g, b]) => (rgbToHex(r, g, b))); | |
promises.push(promise); | |
}); | |
Promise.all(promises) | |
.then((values) => { console.log(values); }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment