Justin
Justin

Reputation: 2049

How to deduce the relative percentage value of a color using a color gradient

I'm need to write something that will take a color (via any format, hex, rgb, etc), and based on where that color would be found on a specific color gradient, a percentage value can be calculated.

Color Scale

   %  HEX       R   G   B     HUE   SATURATION  VALUE
  0%  #FFFFFF   255 255 255   0°    0.0%        100.0%
 10%  #FFE98E   255 233 142   48°   44.3%       100.0%
 25%  #FFD072   255 208 114   40°   55.3%       100.0%
 50%  #FCB119   252 177 25    40°   90.1%       98.8%
 75%  #FA7E21   250 126 33    26°   86.8%       98.0%
100%  #E75800   231 88  0     23°   100.0%      90.6%

(An actual image of the colors can be found in this gist)

For example, if the color ends up being #FFE8BA, then that would land somewhere between 0% and 10%.

Its not so much the specific code I'm asking help for (I haven't even decided what language to use, but it'll likely be either JS or Python), it's more about the specifics on how to analyze a color and compare it to a specific color gradient to return a color.

If anyone has any experience doing something like this, any advice would be appreciated.

Thanks!

Upvotes: 0

Views: 293

Answers (1)

Justin
Justin

Reputation: 2049

Well that was a lot easier than I thought it would be. I was able to find existing code or tools that took care of the hard parts.

In case anyone wants to know how I did it, first I generated a color gradient of 51 colors from #FFFFFF to #E75800 (using this tool). Stored these in an object with keys 0 to 100 (to represent the percentage), skipping every other digit, like so:

var colors = {
    0: "FFFFFF",  2: "FEFBF9",  4: "FEF8F4",  6: "FDF4EF",  8: "FDF1EA", 
   10: "FCEEE5", 12: "FCEAE0", 14: "FBE7DB" // Truncated...
}

Note: You don't need to skip every other digit. I just did that because the took I linked to only allows up to 63 colors to be generated at once (yes, I know I could just run it multiple times)

Then borrowing the getSimilarColors function from this SO post, find the closest match by comparing the provided color to the values within the object created earlier. The key of the element that was a closest match would be the percent.

Thanks.

Upvotes: 1

Related Questions