Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Last active November 3, 2023 07:08
Show Gist options
  • Save wjkoh/de3395e28f39c6e32d0f47fac76db413 to your computer and use it in GitHub Desktop.
Save wjkoh/de3395e28f39c6e32d0f47fac76db413 to your computer and use it in GitHub Desktop.
Go: HSV to RGB
package bake
import (
"errors"
"image/color"
"math"
)
// https://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB
func HSVToRGBA(h float64, s float64, v float64) (*color.RGBA, error) {
if h < 0.0 || h > 1.0 {
return nil, errors.New("hue must be in [0.0, 1.0]")
}
if s < 0.0 || s > 1.0 {
return nil, errors.New("saturation must be in [0.0, 1.0]")
}
if v < 0.0 || v > 1.0 {
return nil, errors.New("lightness must be in [0.0, 1.0]")
}
c := v * s
h_prime := h * 6.0
x := c * (1 - math.Abs(math.Mod(h_prime, 2.0)-1.0))
var r, g, b float64
switch {
case 0 <= h_prime && h_prime < 1:
r, g, b = c, x, 0
case 1 <= h_prime && h_prime < 2:
r, g, b = x, c, 0
case 2 <= h_prime && h_prime < 3:
r, g, b = 0, c, x
case 3 <= h_prime && h_prime < 4:
r, g, b = 0, x, c
case 4 <= h_prime && h_prime < 5:
r, g, b = x, 0, c
case 5 <= h_prime && h_prime < 6:
r, g, b = c, 0, x
}
m := v - c
return &color.RGBA{
uint8((r + m) * 255),
uint8((g + m) * 255),
uint8((b + m) * 255),
255,
}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment