Version 2 of Closest color name

Updated 2003-06-28 01:08:22

Suppose you have a color, perhaps the result of a tk_chooseColor operation, or some sort of "$widget configure -fg" introspection and transformation. Is there a way to say that color in English?

[Still being commented ...]

Sure. Just use the code below:

    proc get_color_name {color_value permitted_list} {
        set least_distance 10000
        set set_name unknown

        if [regexp #(.*) $color_value -> rgb] {
            scan $rgb %2x%2x%2x r0 g0 b0
        } else {
                # Assume it's a known color name.
            foreach {r0 g0 b0} [get_rgb [winfo rgb . $color_value]] {}
        }

        foreach name $permitted_list {
            set list {}
            foreach part [winfo rgb . $name] {
                scan [format %4x $part] %2x%2x first second
                lappend list $first
            }
            foreach {r g b} $list {}
            set d [expr abs($r - $r0) + abs($g - $g0) + abs($b - $b0)]
            if {!$d} {
                return $name
            }
            if {$d < $least_distance} {
                # puts "$name, at ($r, $g, $b), is within $d of ($r0, $g, $b0)."
                set least_distance $d
                set best_name $name
            }
        }
        return "$best_name +/ $least_distance"
    }