Debian Codegraph @

imagex/colorx/colorx.go

raw
1 package colorx
2
3 import (
4 "errors"
5 "image/color"
6 )
7
8 var errInvalidFormat = errors.New("invalid format")
9
10 // ParseHexColor parses a web color given by its hex RGB format.
11 // See https://en.wikipedia.org/wiki/Web_colors for input format.
12 //
13 // For details, see https://stackoverflow.com/a/54200713/1705598
14 func ParseHexColor(s string) (c color.RGBA, err error) {
15 c.A = 0xff
16
17 if s[0] != '#' {
18 return c, errInvalidFormat
19 }
20
21 hexToByte := func(b byte) byte {
22 switch {
23 case b >= '0' && b <= '9':
24 return b - '0'
25 case b >= 'a' && b <= 'f':
26 return b - 'a' + 10
27 case b >= 'A' && b <= 'F':
28 return b - 'A' + 10
29 }
30 err = errInvalidFormat
31 return 0
32 }
33
34 switch len(s) {
35 case 7:
36 c.R = hexToByte(s[1])<<4 + hexToByte(s[2])
37 c.G = hexToByte(s[3])<<4 + hexToByte(s[4])
38 c.B = hexToByte(s[5])<<4 + hexToByte(s[6])
39 case 4:
40 c.R = hexToByte(s[1]) * 17
41 c.G = hexToByte(s[2]) * 17
42 c.B = hexToByte(s[3]) * 17
43 default:
44 err = errInvalidFormat
45 }
46 return
47 }