in reply to Converting hex colors to color safe hex

I take it you have hex colors such as "ab1289" where "ab" is the red value, "12" is the blue value, and "89" is the green value. You want to match these up to the closest analog on some approved list (safe colors).

I'd probably start by writing something that would take such a color and break it into three decimal values using hex. I could store them in a hash mapping the original hex to an array reference with the numbers.

Then, given an unsafe color, compare it using the absolute value (abs) of the difference of the respective values (i.e., abs( $unsafe_red - $safe_red )). You'll get three differences (red, green, blue).

You might want the color that has the smallest combined difference (the minimum of $red_diff+$blue_diff+$green_diff), or you might want to pick a color where the individual differences are small (the minimum of max( $red_diff, $blue_diff, $green_diff )). You can find max() written for you in List::Util. I'm not sure which of those will give better results, but either one should get you "close".

Replies are listed 'Best First'.
Re^2: Converting hex colors to color safe hex
by dhosek (Beadle) on Apr 11, 2008 at 17:38 UTC
    I think you're overthinking the problem. What you're outlining makes sense if you're trying to get a minimal set of colors (adaptive pallet in Adobe-speak), but for going to websafe sets, rounding each color component individually will get the correct result. So you can do something along the lines of int($val/51+0.5)*51 to get yourself to the set of hex values 00, 33, 66, 99, CC, FF.

    But are websafe colors even an issue any more? Who's using 256-color displays these days? This is one of those holdovers from the early days of the web which don't make sense. On the other hand, if you're going to a GIF, then you may want to think about using a proper clustering algorithm to get to the optimal color set. I'd suggest looking at Algorithm::Cluster for that task.

    Donald Hosek, Tech Lead at oversee.net
    L.A. perl people, we're hiring.
Re^2: Converting hex colors to color safe hex
by hushhush (Novice) on Apr 11, 2008 at 16:49 UTC

    thanks for the replies yes, I meant web safe colors. I'd give some example code except I keep deleting it because it's horribly wrong. Getting stuck.

    Basically I"m trying to do given hex color input as so: EEEEEE
    Output should be nearest hex color from the 216 web safe palette: FFFFFF

    I'll see if I can get further with what you've supplied, thanks again.