/
hex.go
51 lines (40 loc) 路 1.09 KB
/
hex.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Package colorcode provides color space definitions
// and methods to convert between them.
package colorcode
import "fmt"
// HexCode represents an HTML color string. Implements
// fmt.Stringer
type HexCode string
// NewHexCode returns a new HexCode built out of a string
func NewHexCode(code string) HexCode {
return HexCode(code)
}
// String returns the string representation of the HexCode
func (cs HexCode) String() string {
return string(cs)
}
// ToRGB converts a HexCode string color into its RGB equivalent
func (cs HexCode) ToRGB() (RGB, error) {
var r, g, b uint8
n, err := fmt.Sscanf(string(cs), "#%2x%2x%2x", &r, &g, &b)
if err != nil || n != 3 {
return RGB{}, err
}
return RGB{r, g, b}, nil
}
// ToHSL converts a HexCode string color to its HSL equivalent
func (cs HexCode) ToHSL() (HSL, error) {
rgb, err := cs.ToRGB()
if err != nil {
return HSL{}, err
}
return rgb.ToHSL(), nil
}
// ToHSV converts a HexCode string color to its HSV equivalent
func (cs HexCode) ToHSV() (HSV, error) {
rgb, err := cs.ToRGB()
if err != nil {
return HSV{}, err
}
return rgb.ToHSV(), nil
}