Version 0 of Closest color name

Updated 2003-06-27 23:27:49

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?

Sure. Just use the code below:

    proc get_color_name {color_value permitted_list} {
        if {![regexp #(.*) $color_value -> rgb]} {
            return $color_value
        }
        scan $rgb %2x%2x%2x r0 g0 b0
        set least_distance 10000
        set set_name unknown
        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"
    }