MCPcopy Index your code
hub / github.com/lucasb-eyer/go-colorful

github.com/lucasb-eyer/go-colorful @v1.4.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.4.0 ↗ · + Follow
303 symbols 992 edges 23 files 141 documented · 47% 323 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

go-colorful

Go Reference go reportcard

A library for playing with colors in Go. Supports Go 1.13 onwards.

Why?

I love games. I make games. I love detail and I get lost in detail. One such detail popped up during the development of Memory Which Does Not Suck, when we wanted the server to assign the players random colors. Sometimes two players got very similar colors, which bugged me. The very same evening, I want hue was the top post on HackerNews' frontpage and showed me how to Do It Right™. Last but not least, there was no library for handling color spaces available in go. Colorful does just that and implements Go's color.Color interface.

What?

Go-Colorful stores colors in RGB and provides methods from converting these to various color-spaces. Currently supported colorspaces are:

  • RGB: All three of Red, Green and Blue in [0..1].
  • HSL: Hue in [0..360], Saturation and Luminance in [0..1]. For legacy reasons; please forget that it exists.
  • HSV: Hue in [0..360], Saturation and Value in [0..1]. You're better off using HCL, see below.
  • Hex RGB: The "internet" color format, as in #FF00FF.
  • Linear RGB: See gamma correct rendering.
  • CIE-XYZ: CIE's standard color space, almost in [0..1].
  • CIE-xyY: encodes chromacity in x and y and luminance in Y, all in [0..1]
  • CIE-L*a*b*: A perceptually uniform color space, i.e. distances are meaningful. L* in [0..1] and a*, b* almost in [-1..1].
  • CIE-L*u*v*: Very similar to CIE-L*a*b*, there is no consensus on which one is "better".
  • CIE-L*C*h° (HCL): This is generally the most useful one; CIE-L*a*b* space in polar coordinates, i.e. a better HSV. H° is in [0..360], C* almost in [0..1] and L* as in CIE-L*a*b*.
  • CIE LCh(uv): Called LuvLCh in code, this is a cylindrical transformation of the CIE-L*u*v* color space. Like HCL above: H° is in [0..360], C* almost in [0..1] and L* as in CIE-L*u*v*.
  • HSLuv: The better alternative to HSL, see here and here. Hue in [0..360], Saturation and Luminance in [0..1].
  • HPLuv: A variant of HSLuv. The color space is smoother, but only pastel colors can be included. Because the valid colors are limited, it's easy to get invalid Saturation values way above 1.0, indicating the color can't be represented in HPLuv because it's not pastel.
  • Oklab: A perceptual color space by Björn Ottosson that improves on CIE-L*a*b* with better perceptual uniformity, especially for blue hues. L in [0..1], a and b roughly in [-0.5..0.5]. See Oklab.
  • Oklch: The cylindrical (polar) representation of Oklab, similar to HCL. L in [0..1], C roughly in [0..0.5], h° in [0..360].

For the colorspaces where it makes sense (XYZ, Lab, Luv, HCl), the D65 is used as reference white by default but methods for using your own reference white are provided.

A coordinate being almost in a range means that generally it is, but for very bright colors and depending on the reference white, it might overflow this range slightly. For example, C* of #0000ff is 1.338.

Unit-tests are provided.

Nice, but what's it useful for?

  • Converting color spaces. Some people like to do that.
  • Blending (interpolating) between colors in a "natural" look by using the right colorspace.
  • Generating random colors under some constraints (e.g. colors of the same shade, or shades of one color.)
  • Generating gorgeous random palettes with distinct colors of a same temperature.

So which colorspace should I use?

It depends on what you want to do. I think the folks from I want hue are on-spot when they say that RGB fits to how screens produce color, CIE L*a*b* fits how humans perceive color and HCL fits how humans think colors.

Whenever you'd use HSV, rather go for CIE-L*C*h°. for fixed lightness L* and chroma C* values, the hue angle h° rotates through colors of the same perceived brightness and intensity.

How?

Installing

Installing the library is as easy as

$ go get github.com/lucasb-eyer/go-colorful

The package can then be used through an

import "github.com/lucasb-eyer/go-colorful"

Basic usage

Create a beautiful blue color using different source space:

// Any of the following should be the same
c := colorful.Color{0.313725, 0.478431, 0.721569}
c, err := colorful.Hex("#517AB8")
if err != nil {
    log.Fatal(err)
}
c = colorful.Hsv(216.0, 0.56, 0.722)
c = colorful.Xyz(0.189165, 0.190837, 0.480248)
c = colorful.Xyy(0.219895, 0.221839, 0.190837)
c = colorful.Lab(0.507850, 0.040585,-0.370945)
c = colorful.Luv(0.507849,-0.194172,-0.567924)
c = colorful.Hcl(276.2440, 0.373160, 0.507849)
c = colorful.OkLab(0.577227, -0.021391, -0.104541)
c = colorful.OkLch(0.577227, 0.106707, 258.435657)
fmt.Printf("RGB values: %v, %v, %v", c.R, c.G, c.B)

And then converting this color back into various color spaces:

hex := c.Hex()
h, s, v := c.Hsv()
x, y, z := c.Xyz()
x, y, Y := c.Xyy()
l, a, b := c.Lab()
l, u, v := c.Luv()
h, c, l := c.Hcl()
l, a, b = c.OkLab()
l, c, h = c.OkLch()

Note that, because of Go's unfortunate choice of requiring an initial uppercase, the name of the functions relating to the xyY space are just off. If you have any good suggestion, please open an issue. (I don't consider XyY good.)

The color.Color interface

Because a colorful.Color implements Go's color.Color interface (found in the image/color package), it can be used anywhere that expects a color.Color.

Furthermore, you can convert anything that implements the color.Color interface into a colorful.Color using the MakeColor function:

c, ok := colorful.MakeColor(color.Gray16{12345})

Caveat: Be aware that this latter conversion (using MakeColor) hits a corner-case when alpha is exactly zero. Because color.Color uses pre-multiplied alpha colors, this means the RGB values are lost (set to 0) and it's impossible to recover them. In such a case MakeColor will return false as its second value.

Comparing colors

In the RGB color space, the Euclidean distance between colors doesn't correspond to visual/perceptual distance. This means that two pairs of colors which have the same distance in RGB space can look much further apart. This is fixed by the CIE-L*a*b*, CIE-L*u*v* and CIE-L*C*h° color spaces. Thus you should only compare colors in any of these space. (Note that the distance in CIE-L*a*b* and CIE-L*C*h° are the same, since it's the same space but in cylindrical coordinates)

Color distance comparison

The two colors shown on the top look much more different than the two shown on the bottom. Still, in RGB space, their distance is the same. Here is a little example program which shows the distances between the top two and bottom two colors in RGB, CIE-L*a*b* and CIE-L*u*v* space. You can find it in doc/colordist/colordist.go.

package main

import "fmt"
import "github.com/lucasb-eyer/go-colorful"

func main() {
    c1a := colorful.Color{150.0 / 255.0, 10.0 / 255.0, 150.0 / 255.0}
    c1b := colorful.Color{53.0 / 255.0, 10.0 / 255.0, 150.0 / 255.0}
    c2a := colorful.Color{10.0 / 255.0, 150.0 / 255.0, 50.0 / 255.0}
    c2b := colorful.Color{99.9 / 255.0, 150.0 / 255.0, 10.0 / 255.0}

    fmt.Printf("DistanceRgb:       c1: %v\tand c2: %v\n", c1a.DistanceRgb(c1b), c2a.DistanceRgb(c2b))
    fmt.Printf("DistanceLab:       c1: %v\tand c2: %v\n", c1a.DistanceLab(c1b), c2a.DistanceLab(c2b))
    fmt.Printf("DistanceLuv:       c1: %v\tand c2: %v\n", c1a.DistanceLuv(c1b), c2a.DistanceLuv(c2b))
    fmt.Printf("DistanceCIE76:     c1: %v\tand c2: %v\n", c1a.DistanceCIE76(c1b), c2a.DistanceCIE76(c2b))
    fmt.Printf("DistanceCIE94:     c1: %v\tand c2: %v\n", c1a.DistanceCIE94(c1b), c2a.DistanceCIE94(c2b))
    fmt.Printf("DistanceCIEDE2000: c1: %v\tand c2: %v\n", c1a.DistanceCIEDE2000(c1b), c2a.DistanceCIEDE2000(c2b))
}

Running the above program shows that you should always prefer any of the CIE distances:

$ go run colordist.go
DistanceRgb:       c1: 0.3803921568627451   and c2: 0.3858713931171159
DistanceLab:       c1: 0.32048458312798056  and c2: 0.24397151758565272
DistanceLuv:       c1: 0.5134369614199698   and c2: 0.2568692839860636
DistanceCIE76:     c1: 0.32048458312798056  and c2: 0.24397151758565272
DistanceCIE94:     c1: 0.19799168128511324  and c2: 0.12207136371167401
DistanceCIEDE2000: c1: 0.17274551120971166  and c2: 0.10665210031428465

It also shows that DistanceLab is more formally known as DistanceCIE76 and has been superseded by the slightly more accurate, but much more expensive DistanceCIE94 and DistanceCIEDE2000.

Note that AlmostEqualRgb is provided mainly for (unit-)testing purposes. Use it only if you really know what you're doing. It will eat your cat.

Blending colors

Blending is highly connected to distance, since it basically "walks through" the colorspace thus, if the colorspace maps distances well, the walk is "smooth".

Colorful comes with blending functions in RGB, HSV, Oklab, Oklch, and any of the CIE-LAB spaces. Of course, you'd rather want to use the blending functions of the LAB spaces since these spaces map distances well but, just in case, here is an example showing you how the blendings (#fdffcc to #242a42) are done in the various spaces:

Blending colors in different spaces.

What you see is that HSV is really bad: it adds some green, which is not present in the original colors at all! RGB is much better, but it stays light a little too long. LUV and LAB both hit the right lightness but LAB has a little more color. HCL works in the same vein as HSV (both cylindrical interpolations) but it does it right in that there is no green appearing and the lightness changes in a linear manner.

While this seems all good, you need to know one thing: When interpolating in any of the CIE color spaces, you might get invalid RGB colors! This is important if the starting and ending colors are user-input or random. An example of where this happens is when blending between #eeef61 and #1e3140:

Invalid RGB colors may crop up when blending in CIE spaces.

You can test whether a color is a valid RGB color by calling the IsValid method and indeed, calling IsValid will return false for the redish colors on the bottom. One way to "fix" this is to get a valid color close to the invalid one by calling Clamped, which always returns a nearby valid color. Doing this, we get the following result, which is satisfactory:

Fixing invalid RGB colors by clamping them to the valid range.

The following is the code creating the above three images; it can be found in doc/colorblend/colorblend.go

package main

import "fmt"
import "github.com/lucasb-eyer/go-colorful"
import "image"
import "image/draw"
import "image/png"
import "os"

func main() {
    blocks := 10
    blockw := 40
    img := image.NewRGBA(image.Rect(0,0,blocks*blockw,200))

    c1, _ := colorful.Hex("#fdffcc")
    c2, _ := colorful.Hex("#242a42")

    // Use these colors to get invalid RGB in the gradient.
    //c1, _ := colorful.Hex("#EEEF61")
    //c2, _ := colorful.Hex("#1E3140")

    for i := 0 ; i < blocks ; i++ {
        draw.Draw(img, image.Rect(i*blockw,  0,(i+1)*blockw, 40), &image.Uniform{c1.BlendHsv(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
        draw.Draw(img, image.Rect(i*blockw, 40,(i+1)*blockw, 80), &image.Uniform{c1.BlendLuv(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
        draw.Draw(img, image.Rect(i*blockw, 80,(i+1)*blockw,120), &image.Uniform{c1.BlendRgb(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
        draw.Draw(img, image.Rect(i*blockw,120,(i+1)*blockw,160), &image.Uniform{c1.BlendLab(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
        draw.Draw(img, image.Rect(i*blockw,160,(i+1)*blockw,200), &image.Uniform{c1.BlendHcl(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)

        // This can be used to "fix" invalid colors in the gradient.
        //draw.Draw(img, image.Rect(i*blockw,160,(i+1)*blockw,200), &image.Uniform{c1.BlendHcl(c2, float64(i)/float64(blocks-1)).Clamped()}, image.Point{}, draw.Src)
    }

    toimg, err := os.Create("colorblend.png")
    if err != nil {
        fmt.Printf("Error: %v", err)
        return
    }
    defer toimg.Close()

    png.Encode(toimg, img)
}

Generating color gradients

A very common reason to blend colors is creating gradients. There is an example program in doc/gradientgen.go; it doesn't use any API which hasn't been used in the previous example code, so I won't bother pasting the code in here. Just look at that gorgeous gradient it generated in HCL space:

"Spectral" colorbrewer gradient in HCL space.

Getting random colors

It is sometimes necessary to generate random colors. You could simply do this on your own by generating colors with random values. By restricting the random values to a range smaller than [0..1] and using a space such as CIE-H*C*l° or HSV, you can generate both random shades of a color or rando

Extension points exported contracts — how you extend this code

RandInterface (Interface)
(no doc) [1 implementers]
rand.go

Core symbols most depended-on inside this repo

Hex
called by 52
colors.go
sq
called by 49
colors.go
Float64
called by 32
rand.go
AlmostEqualRgb
called by 23
colors.go
Hex
called by 20
colors.go
Lab
called by 18
colors.go
Xyz
called by 15
colors.go
IsValid
called by 13
colors.go

Shape

Function 218
Method 71
Struct 8
TypeAlias 5
Interface 1

Languages

Go100%

Modules by API surface

colors.go97 symbols
colors_test.go47 symbols
widegamut.go34 symbols
widegamut_test.go23 symbols
hsluv.go16 symbols
sort.go11 symbols
hexcolor.go11 symbols
soft_palettegen.go10 symbols
colorgens.go10 symbols
hsluv_test.go8 symbols
rand.go7 symbols
warm_palettegen.go4 symbols

For agents

$ claude mcp add go-colorful \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact