67 lines
1.1 KiB
Go
67 lines
1.1 KiB
Go
package color
|
|
|
|
import (
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
type RGB struct {
|
|
Red int
|
|
Green int
|
|
Blue int
|
|
}
|
|
|
|
func MustParseHex(hexColor string) *RGB {
|
|
c, err := ParseHex(hexColor)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return c
|
|
}
|
|
|
|
func ParseHex(hexColor string) (*RGB, error) {
|
|
hexColor = strings.TrimPrefix(hexColor, "#")
|
|
|
|
// Convert to individual parts
|
|
var rh, gh, bh string
|
|
switch len(hexColor) {
|
|
case 3:
|
|
rh, gh, bh = hexColor[:1]+hexColor[:1], hexColor[1:2]+hexColor[1:2], hexColor[2:3]+hexColor[2:3]
|
|
case 6:
|
|
rh, gh, bh = hexColor[0:2], hexColor[2:4], hexColor[4:6]
|
|
default:
|
|
return nil, errors.New("invalid hex string")
|
|
}
|
|
|
|
// Convert to bytes
|
|
rb, err := hex.DecodeString(rh)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gb, err := hex.DecodeString(gh)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
bb, err := hex.DecodeString(bh)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &RGB{
|
|
Red: int(rb[0]),
|
|
Green: int(gb[0]),
|
|
Blue: int(bb[0]),
|
|
}, nil
|
|
}
|
|
|
|
// String returns an r;g;b representation of an RGB
|
|
func (r *RGB) String() string {
|
|
return r.format()
|
|
}
|
|
|
|
func (r *RGB) format() string {
|
|
return fmt.Sprintf("%d;%d;%d", r.Red, r.Green, r.Blue)
|
|
}
|