github.com/status-im/status-go@v1.1.0/images/initials.go (about) 1 package images 2 3 import ( 4 "bytes" 5 "image/color" 6 "image/png" 7 "io/ioutil" 8 "strings" 9 10 "github.com/fogleman/gg" 11 "golang.org/x/image/font" 12 "golang.org/x/image/font/opentype" 13 ) 14 15 type RGBA struct { 16 R, G, B, A float64 17 } 18 19 var parsedFont *opentype.Font = nil 20 21 func ExtractInitials(fullName string, amountInitials int) string { 22 if fullName == "" { 23 return "" 24 } 25 var initials strings.Builder 26 namesList := strings.Fields(fullName) 27 for _, name := range namesList { 28 if len(initials.String()) >= amountInitials { 29 break 30 } 31 if name != "" { 32 initials.WriteString(strings.ToUpper(name[0:1])) 33 } 34 } 35 return initials.String() 36 } 37 38 // GenerateInitialsImage uppercaseRatio is <height of any upper case> / dc.FontHeight() (line height) 39 // 0.60386123 for Inter-UI-Medium.otf 40 func GenerateInitialsImage(initials string, bgColor, fontColor color.Color, fontFile string, size int, fontSize float64, uppercaseRatio float64) ([]byte, error) { 41 // Load otf file 42 fontBytes, err := ioutil.ReadFile(fontFile) 43 if err != nil { 44 return nil, err 45 } 46 47 if parsedFont == nil { 48 parsedFont, err = opentype.Parse(fontBytes) 49 if err != nil { 50 return nil, err 51 } 52 } 53 54 halfSize := float64(size / 2) 55 56 dc := gg.NewContext(size, size) 57 dc.DrawCircle(halfSize, halfSize, halfSize) 58 dc.SetColor(bgColor) 59 dc.Fill() 60 61 // Load font 62 face, err := opentype.NewFace(parsedFont, &opentype.FaceOptions{ 63 Size: fontSize, 64 DPI: 72, 65 Hinting: font.HintingNone, 66 }) 67 if err != nil { 68 return nil, err 69 } 70 dc.SetFontFace(face) 71 72 // Draw initials 73 dc.SetColor(fontColor) 74 75 dc.DrawStringAnchored(initials, halfSize, halfSize, 0.5, uppercaseRatio/2) 76 77 img := dc.Image() 78 buffer := new(bytes.Buffer) 79 err = png.Encode(buffer, img) 80 if err != nil { 81 return nil, err 82 } 83 return buffer.Bytes(), nil 84 }