Function to convert webcolor html colour name to hex in Go | DarkOrange -> #FF8C00

Simple solution

The package golang.org/x/image/colornames also contains an exported Map variable which maps from lowercased color names to color.RGBA.

So simply use this map to lookup the color for a name, and convert the RGB components to hex representation:

func convertWebToHex(webcolorname string) (hexcolor string) {
    c, ok := colornames.Map[webcolorname]
    if !ok {
        // Unknown name
        return ""
    }
    return fmt.Sprintf("#%02X%02X%02X", c.R, c.G, c.B)
}

Testing it:

names := []string{
    "red",
    "yellow",
    "lightyellow",
    "invalid",
}
for _, name := range names {
    fmt.Printf("%-12s: %s\n", name, convertWebToHex(name))
}

Which outputs (try it on the Go Playground):

red         : #FF0000
yellow      : #FFFF00
lightyellow : #FFFFE0
invalid     : 

Case insensitive solution

If you want to lookup colors in a case insensitive manner, use strings.ToLower() to convert the name to lowercase, then proceed to lookup:

func convertWebToHex(webcolorname string) (hexcolor string) {
    c, ok := colornames.Map[strings.ToLower(webcolorname)]
    if !ok {
        // Unknown name
        return ""
    }
    return fmt.Sprintf("#%02X%02X%02X", c.R, c.G, c.B)
}

Testing it:

names := []string{
    "Red",
    "yELLOW",
    "LightYellow",
    "invalid",
}
for _, name := range names {
    fmt.Printf("%-12s: %s\n", name, convertWebToHex(name))
}

Which outputs (try it on the Go Playground):

Red         : #FF0000
yELLOW      : #FFFF00
LightYellow : #FFFFE0
invalid     : 

Pre-calculated hex values

Also note that if you have to do these lookups frequently, it might be profitable to create your own map, where you map from color name to the generated hex string, so you don’t have to convert from color.RGBA to hex string all the time.

This is how this pre-calculated map solution looks like:

var colorMap = map[string]string{}

func init() {
    for name, c := range colornames.Map {
        colorMap[name] = fmt.Sprintf("#%02X%02X%02X", c.R, c.G, c.B)
    }
}

func convertWebToHex(webcolorname string) (hexcolor string) {
    // invalid color results in the zero value ""
    return colorMap[strings.ToLower(webcolorname)]
}

Testing and output is the same. Try this one on the Go Playground.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top