File: rgb_from_hex.go

package info (click to toggle)
golang-github-pterm-pterm 0.12.79-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,640 kB
  • sloc: makefile: 4
file content (35 lines) | stat: -rw-r--r-- 738 bytes parent folder | download
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
}