lokesh / color-thief

Grab the color palette from an image using just Javascript. Works in the browser and in Node.
https://lokeshdhakar.com/projects/color-thief/
MIT License
12.61k stars 1.31k forks source link

Lightest color from the color palette #50

Open tiagogon opened 10 years ago

tiagogon commented 10 years ago

Since i would like to use this scrip to get a color for a background (that i want to be light), I would like to know if there is a way to get from the color palette the lightest color?

Thank you!

Pluto1010 commented 8 years ago

Maybe this is something for you: https://gist.github.com/Pluto1010/f26beed7fdebfb2e2110

AlfredJKwack commented 8 years ago

I know this is an old thread but just in case someone comes across this here's a solution.

The calculation used is Relative Luminance. There are other options though. You should also note that the function will only return one color, even if there are several in the palette which have the same luminance value.

var lightestColor = palette.reduce(function(previousValue, currentValue){
    var currLightNess = (0.2126*currentValue[0] + 0.7152*currentValue[1] + 0.0722*currentValue[2]);
    var prevLightNess = (0.2126*previousValue[0] + 0.7152*previousValue[1] + 0.0722*previousValue[2]);
    return (prevLightNess < currLightNess) ? currentValue : previousValue;
});

Assuming the below input:

var palette = [[58,40,29],[179,132,42],[110,204,222],[213,219,185],[162,184,117],[129,119,105],[43,125,148],[172,198,208],[44,68,132]];

you'll get a return value of:

lightestColor = [213, 219, 185]