forked from ae0000/avatar
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathavatar.go
277 lines (229 loc) · 5.94 KB
/
avatar.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package avatar
import (
"bufio"
"bytes"
"embed"
"fmt"
"image"
"image/draw"
"image/png"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
)
const (
defaultfontFace = "fonts/Roboto-Bold.ttf" //SourceSansVariable-Roman.ttf"
fontSize = 60.0
imageWidth = 100.0
imageHeight = 100.0
dpi = 72.0
spacer = 4
textY = 71
)
//go:embed fonts/*
var fonts embed.FS
// ToDisk saves the image to disk
func ToDisk(initials, path string) {
saveToDisk(initials, path, "", "")
}
// ToDiskCustom saves the image to disk
func ToDiskCustom(initials, path, bgColor, fontColor string) {
saveToDisk(initials, path, bgColor, fontColor)
}
// saveToDisk saves the image to disk
func saveToDisk(initials, path, bgColor, fontColor string) {
bgC, fgC := parseOrDefault(initials, bgColor, fontColor)
rgba, err := createAvatar(initials, bgC, fgC)
if err != nil {
log.Println(err)
return
}
// Save image to disk
out, err := os.Create(path)
if err != nil {
log.Println(err)
os.Exit(1)
}
defer out.Close()
b := bufio.NewWriter(out)
err = png.Encode(b, rgba)
if err != nil {
log.Println(err)
os.Exit(1)
}
err = b.Flush()
if err != nil {
log.Println(err)
os.Exit(1)
}
}
// ToHTTP sends the image to a http.ResponseWriter (as a PNG)
func ToHTTP(initials string, w http.ResponseWriter) {
saveToHTTP(initials, "", "", w)
}
// ToHTTPCustom sends the image to a http.ResponseWriter (as a PNG)
func ToHTTPCustom(initials, bgColor, fontColor string, w http.ResponseWriter) {
saveToHTTP(initials, bgColor, fontColor, w)
}
// saveToHTTP sends the image to a http.ResponseWriter (as a PNG)
func saveToHTTP(initials, bgColor, fontColor string, w http.ResponseWriter) {
bgC, fgC := parseOrDefault(initials, bgColor, fontColor)
rgba, err := createAvatar(initials, bgC, fgC)
if err != nil {
log.Println(err)
return
}
b := new(bytes.Buffer)
key := fmt.Sprintf("avatar%s", initials) // for Etag
err = png.Encode(b, rgba)
if err != nil {
log.Println("unable to encode image.")
}
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Length", strconv.Itoa(len(b.Bytes())))
w.Header().Set("Cache-Control", "max-age=2592000") // 30 days
w.Header().Set("Etag", `"`+key+`"`)
if _, err := w.Write(b.Bytes()); err != nil {
log.Println("unable to write image.")
}
}
// ToSlice simply buffers the image and returns the byte slice (as a PNG)
func ToSlice(initials string, colorSalt int) ([]byte, error) {
bgC, fgC := saltedColor(initials, colorSalt)
rgba, err := createAvatar(initials, bgC, fgC)
if err != nil {
log.Println(err)
return nil, err
}
buf := new(bytes.Buffer)
err = png.Encode(buf, rgba)
if nil == err {
return buf.Bytes(), err
} else {
log.Println("unable to encode image.")
return nil, err
}
}
// ToSlice simply buffers the image and returns the byte slice (as a PNG)
func ToSliceCustomColors(initials string, bgColor, fontColor string) ([]byte, error) {
bgC, fgC := parseOrDefault(initials, bgColor, fontColor)
rgba, err := createAvatar(initials, bgC, fgC)
if err != nil {
log.Println(err)
return nil, err
}
buf := new(bytes.Buffer)
err = png.Encode(buf, rgba)
if nil == err {
return buf.Bytes(), err
} else {
log.Println("unable to encode image.")
return nil, err
}
}
func cleanString(incoming string) string {
incoming = strings.TrimSpace(incoming)
// If its something like "firstname surname" get the initials out
split := strings.Split(incoming, " ")
if len(split) == 2 {
incoming = split[0][0:1] + split[1][0:1]
}
// Max length of 2
if len(incoming) > 2 {
incoming = incoming[0:2]
}
// To upper and trimmed
return strings.ToUpper(strings.TrimSpace(incoming))
}
func getFont(fontPath string) (theFont *truetype.Font, err error) {
if fontPath == "" {
fontPath = defaultfontFace
}
// Read the font data.
var fontBytes []byte
fontBytes, err = fonts.ReadFile(fontPath)
if err != nil {
return nil, err
}
return freetype.ParseFont(fontBytes)
}
var imageCache sync.Map
func getImage(initials string) *image.RGBA {
value, ok := imageCache.Load(initials)
if !ok {
return nil
}
image, ok2 := value.(*image.RGBA)
if !ok2 {
return nil
}
return image
}
func setImage(initials string, image *image.RGBA) {
imageCache.Store(initials, image)
}
func createAvatar(initials string, bgColor, fontColor *image.Uniform) (*image.RGBA, error) {
// Make sure the string is OK
text := cleanString(initials)
// Check cache
cachedImage := getImage(text)
if cachedImage != nil {
return cachedImage, nil
}
// Load and get the font
f, err := getFont(defaultfontFace)
if err != nil {
return nil, err
}
rgba := image.NewRGBA(image.Rect(0, 0, imageWidth, imageHeight))
draw.Draw(rgba, rgba.Bounds(), bgColor, image.ZP, draw.Src)
c := freetype.NewContext()
c.SetDPI(dpi)
c.SetFont(f)
c.SetFontSize(fontSize)
c.SetClip(rgba.Bounds())
c.SetDst(rgba)
c.SetSrc(fontColor)
c.SetHinting(font.HintingFull)
// We need to convert the font into a "font.Face" so we can read the glyph
// info
to := truetype.Options{}
to.Size = fontSize
face := truetype.NewFace(f, &to)
// Calculate the widths and print to image
xPoints := []int{0, 0}
textWidths := []int{0, 0}
// Get the widths of the text characters
for i, char := range text {
width, ok := face.GlyphAdvance(rune(char))
if !ok {
return nil, err
}
textWidths[i] = int(float64(width) / 64)
}
// TODO need some tests for this
if len(textWidths) == 1 {
textWidths[1] = 0
}
// Get the combined width of the characters
combinedWidth := textWidths[0] + spacer + textWidths[1]
// Draw first character
xPoints[0] = int((imageWidth - combinedWidth) / 2)
xPoints[1] = int(xPoints[0] + textWidths[0] + spacer)
for i, char := range text {
pt := freetype.Pt(xPoints[i], textY)
_, err := c.DrawString(string(char), pt)
if err != nil {
return nil, err
}
}
// Cache it
setImage(text, rgba)
return rgba, nil
}