forked from ae0000/avatar
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpalette.go
105 lines (88 loc) · 1.95 KB
/
palette.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package avatar
import (
"bufio"
"encoding/hex"
"errors"
"image/color"
"io/fs"
"net/http"
"strconv"
"strings"
)
func HexToColor(hexColor string) (color.Color, error) {
b, err := hex.DecodeString(hexColor)
if err != nil {
return nil, err
}
if len(b) == 4 {
return color.RGBA{b[0], b[1], b[2], b[3]}, nil
} else if len(b) == 3 {
return color.RGBA{b[0], b[1], b[2], 255}, nil
}
return nil, errors.New("Not valid RGB(A) Hex Color")
}
func LoadHex(fs fs.FS, fname string) (color.Palette, error) {
var err error
var colors color.Palette
file, err := fs.Open(fname)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) > 0 {
c, err := HexToColor(line)
if err != nil {
return colors, err
}
colors = append(colors, c)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return colors, err
}
func LoadGPL(fs http.FileSystem, fname string) (color.Palette, error) {
var err error
var colors color.Palette
file, err := fs.Open(fname)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) > 0 {
if line[0] != '#' {
if !strings.HasPrefix(line, "Name:") &&
!strings.HasPrefix(line, "Columns:") {
pieces := strings.Split(line, "\t")
if len(pieces) >= 3 {
rb, err := strconv.ParseUint(pieces[0], 10, 8)
if err != nil {
return colors, err
}
gb, err := strconv.ParseUint(pieces[1], 10, 8)
if err != nil {
return colors, err
}
bb, err := strconv.ParseUint(pieces[2], 10, 8)
if err != nil {
return colors, err
}
c := color.RGBA{byte(rb), byte(gb), byte(bb), 255}
colors = append(colors, c)
}
}
}
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return colors, err
}