-
Notifications
You must be signed in to change notification settings - Fork 44
/
govatar.go
183 lines (161 loc) · 4.18 KB
/
govatar.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package govatar
import (
"bytes"
"embed"
"errors"
"hash/fnv"
"image"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"io/fs"
"math/rand"
"os"
"path"
"path/filepath"
"sort"
"strings"
"time"
)
var ErrUnsupportedGender = errors.New("unsupported gender")
type person struct {
Clothes []string
Eye []string
Face []string
Hair []string
Mouth []string
}
type store struct {
Background []string
Male person
Female person
}
var assetsStore *store
// Gender represents gender type
type Gender int
// Male and female constants
const (
MALE Gender = iota
FEMALE
)
//go:embed data/*
var dataFS embed.FS
func init() {
male := getPerson(MALE)
female := getPerson(FEMALE)
assetsStore = &store{Background: mustAssetsList("data/background"), Male: male, Female: female}
rand.Seed(time.Now().UTC().UnixNano())
}
// Generate generates random avatar
func Generate(gender Gender) (image.Image, error) {
return GenerateForUsername(gender, time.Now().String())
}
// GenerateFile generates random avatar and save it to specified file.
// Image format depends on file extension (jpeg, jpg, png, gif). Default is png
func GenerateFile(gender Gender, filePath string) error {
img, err := Generate(gender)
if err != nil {
return err
}
return saveToFile(img, filePath)
}
// GenerateForUsername generates avatar for username
func GenerateForUsername(gender Gender, username string) (image.Image, error) {
h := fnv.New32a()
_, err := h.Write([]byte(username))
if err != nil {
return nil, err
}
switch gender {
case MALE:
return randomAvatar(assetsStore.Male, int64(h.Sum32()))
case FEMALE:
return randomAvatar(assetsStore.Female, int64(h.Sum32()))
default:
return nil, ErrUnsupportedGender
}
}
// GenerateFileForUsername generates avatar for username and save it to specified file.
// Image format depends on file extension (jpeg, jpg, png, gif). Default is png
func GenerateFileForUsername(gender Gender, username string, filePath string) error {
img, err := GenerateForUsername(gender, username)
if err != nil {
return err
}
return saveToFile(img, filePath)
}
func saveToFile(img image.Image, filePath string) error {
outFile, err := os.Create(filePath)
if err != nil {
return err
}
defer outFile.Close()
switch strings.ToLower(filepath.Ext(filePath)) {
case ".jpeg", ".jpg":
err = jpeg.Encode(outFile, img, &jpeg.Options{Quality: 80})
case ".gif":
err = gif.Encode(outFile, img, nil)
default:
err = png.Encode(outFile, img)
}
return err
}
func randomAvatar(p person, seed int64) (image.Image, error) {
rnd := rand.New(rand.NewSource(seed))
avatar := image.NewRGBA(image.Rect(0, 0, 400, 400))
var err error
err = drawImg(avatar, randStringSliceItem(rnd, assetsStore.Background), err)
err = drawImg(avatar, randStringSliceItem(rnd, p.Face), err)
err = drawImg(avatar, randStringSliceItem(rnd, p.Clothes), err)
err = drawImg(avatar, randStringSliceItem(rnd, p.Mouth), err)
err = drawImg(avatar, randStringSliceItem(rnd, p.Hair), err)
err = drawImg(avatar, randStringSliceItem(rnd, p.Eye), err)
return avatar, err
}
func drawImg(dst draw.Image, asset string, err error) error {
if err != nil {
return err
}
src, _, err := image.Decode(bytes.NewReader(mustAsset(asset)))
if err != nil {
return err
}
draw.Draw(dst, dst.Bounds(), src, image.Point{0, 0}, draw.Over)
return nil
}
func mustAsset(fPath string) []byte {
b, err := fs.ReadFile(dataFS, fPath)
if err != nil {
panic(err)
}
return b
}
func getPerson(gender Gender) person {
var genderPath string
switch gender {
case FEMALE:
genderPath = "female"
case MALE:
genderPath = "male"
}
return person{
Clothes: mustAssetsList("data/" + genderPath + "/clothes"),
Eye: mustAssetsList("data/" + genderPath + "/eye"),
Face: mustAssetsList("data/" + genderPath + "/face"),
Hair: mustAssetsList("data/" + genderPath + "/hair"),
Mouth: mustAssetsList("data/" + genderPath + "/mouth"),
}
}
func mustAssetsList(dir string) []string {
dirEntries, err := fs.ReadDir(dataFS, dir)
if err != nil {
panic(err)
}
assets := make([]string, len(dirEntries))
for i, dirEntry := range dirEntries {
assets[i] = path.Join(dir, dirEntry.Name())
}
sort.Sort(naturalSort(assets))
return assets
}