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.67k stars 1.31k forks source link

RGB to HEX Conversion Correction #203

Closed Tes3awy closed 3 years ago

Tes3awy commented 3 years ago

Hello @lokesh,

Regarding the conversion used in the FAQ section is probably incomplete. Straight to the point. If Color Thief returns arrays of colors with something like:

[8,12,12]
[24,28,14]
[4,20,11]

The conversion rule used, in the FAQ section, will convert those like (respectively)

#8CC
#181CE
#414B

which are invalid CSS HEX colors.

I came up with a solution to this by adding a leading 0 if the length of the R, G, or B channel is less than 2 after conversion to base16. Here is a snippet of what I mean.

var r = color[0];
var g = color[1];
var b = color[2];
var hexR = r.toString(16);
var hexG = g.toString(16);
var hexB = b.toString(16);
hexR.length < 2 ? (hexR = hexR.padStart(2, '0')) : hexR;
hexG.length < 2 ? (hexG = hexG.padStart(2, '0')) : hexG;
hexB.length < 2 ? (hexB = hexB.padStart(2, '0')) : hexB;

You can also check this demo out to know what I exactly mean. Thank you.

Tes3awy commented 3 years ago

Any updates?