-
Notifications
You must be signed in to change notification settings - Fork 0
/
initialize.go
72 lines (67 loc) · 1.45 KB
/
initialize.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
package imagegenerator
import (
"image"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"github.com/hmmftg/image/bmp"
"github.com/hmmftg/image/font/opentype"
)
func exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func LoadFonts(src string) (map[string]opentype.Font, error) {
if !exists(src) {
return nil, nil
}
fontList, err := os.ReadDir(src)
if err != nil {
return nil, err
}
fonts := make(map[string]opentype.Font, 0)
for _, fontName := range fontList {
fontBytes, err := os.ReadFile(filepath.Join(src, fontName.Name()))
if err != nil {
return nil, err
}
f, err := opentype.Parse(fontBytes)
if err != nil {
return nil, err
}
fonts[fontName.Name()] = *f
}
return fonts, nil
}
func LoadImages(src string) (map[string]image.Image, error) {
if !exists(src) {
return nil, nil
}
imageList, err := os.ReadDir(src)
if err != nil {
return nil, err
}
fonts := make(map[string]image.Image, 0)
for _, imageName := range imageList {
imageFile, err := os.Open(filepath.Join(src, imageName.Name()))
if err != nil {
return nil, err
}
extention := filepath.Ext(imageFile.Name())
var imageData image.Image
switch extention {
case ".png":
imageData, err = png.Decode(imageFile)
case ".bmp":
imageData, err = bmp.Decode(imageFile)
case ".jpg":
imageData, err = jpeg.Decode(imageFile)
}
if err != nil {
return nil, err
}
fonts[imageName.Name()] = imageData
}
return fonts, nil
}