-
Notifications
You must be signed in to change notification settings - Fork 242
/
initials.go
84 lines (71 loc) · 1.73 KB
/
initials.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
package images
import (
"bytes"
"image/color"
"image/png"
"io/ioutil"
"strings"
"github.com/fogleman/gg"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
)
type RGBA struct {
R, G, B, A float64
}
var parsedFont *opentype.Font = nil
func ExtractInitials(fullName string, amountInitials int) string {
if fullName == "" {
return ""
}
var initials strings.Builder
namesList := strings.Fields(fullName)
for _, name := range namesList {
if len(initials.String()) >= amountInitials {
break
}
if name != "" {
initials.WriteString(strings.ToUpper(name[0:1]))
}
}
return initials.String()
}
// GenerateInitialsImage uppercaseRatio is <height of any upper case> / dc.FontHeight() (line height)
// 0.60386123 for Inter-UI-Medium.otf
func GenerateInitialsImage(initials string, bgColor, fontColor color.Color, fontFile string, size int, fontSize float64, uppercaseRatio float64) ([]byte, error) {
// Load otf file
fontBytes, err := ioutil.ReadFile(fontFile)
if err != nil {
return nil, err
}
if parsedFont == nil {
parsedFont, err = opentype.Parse(fontBytes)
if err != nil {
return nil, err
}
}
halfSize := float64(size / 2)
dc := gg.NewContext(size, size)
dc.DrawCircle(halfSize, halfSize, halfSize)
dc.SetColor(bgColor)
dc.Fill()
// Load font
face, err := opentype.NewFace(parsedFont, &opentype.FaceOptions{
Size: fontSize,
DPI: 72,
Hinting: font.HintingNone,
})
if err != nil {
return nil, err
}
dc.SetFontFace(face)
// Draw initials
dc.SetColor(fontColor)
dc.DrawStringAnchored(initials, halfSize, halfSize, 0.5, uppercaseRatio/2)
img := dc.Image()
buffer := new(bytes.Buffer)
err = png.Encode(buffer, img)
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}