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
|
package putils
import (
"strconv"
"strings"
"github.com/pterm/pterm"
)
// RGBFromHEX converts a HEX and returns a new RGB.
// If the hex code is not valid it returns pterm.ErrHexCodeIsInvalid.
func RGBFromHEX(hex string) (pterm.RGB, error) {
hex = strings.ToLower(hex)
hex = strings.ReplaceAll(hex, "#", "")
hex = strings.ReplaceAll(hex, "0x", "")
if len(hex) == 3 {
hex = string([]byte{hex[0], hex[0], hex[1], hex[1], hex[2], hex[2]})
}
if len(hex) != 6 {
return pterm.RGB{}, pterm.ErrHexCodeIsInvalid
}
i64, err := strconv.ParseInt(hex, 16, 32)
if err != nil {
return pterm.RGB{}, err
}
c := int(i64)
return pterm.RGB{
R: uint8(c >> 16),
G: uint8((c & 0x00FF00) >> 8),
B: uint8(c & 0x0000FF),
}, nil
}
|