-
Notifications
You must be signed in to change notification settings - Fork 61
/
fs.go
103 lines (93 loc) · 2.29 KB
/
fs.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
package gocaptcha
import (
"embed"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"io/fs"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
//go:embed fonts
var _fs embed.FS
var ioFS fs.FS = _fs
func FileSystem(fs embed.FS) error {
err := readFontFromFS(fs)
if err != nil {
return err
}
ioFS = fs
return nil
}
//获取指定目录下的所有文件,不进入下一级目录搜索,可以匹配后缀过滤。
func ReadFonts(dirPth string, suffix string) (err error) {
fontFamily = fontFamily[:0]
dir, err := ioutil.ReadDir(dirPth)
if err != nil {
return err
}
suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写
for _, fi := range dir {
if fi.IsDir() { // 忽略目录
continue
}
if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) { //匹配文件
fontFamily = append(fontFamily, filepath.Join(dirPth, fi.Name()))
}
}
ioFS = os.DirFS(dirPth)
return nil
}
//获取所及字体.
func RandFontFamily() (*truetype.Font, error) {
fontFile := fontFamily[r.Intn(len(fontFamily))]
fontBytes, err := ReadFile(fontFile)
if err != nil {
log.Printf("读取文件失败 -> %s - %+v\n", fontFile, err)
return nil, err
}
f, err := freetype.ParseFont(fontBytes)
if err != nil {
log.Printf("解析字体内容试标 -> %s - %+v\n", fontFile, err)
return nil, err
}
return f, nil
}
//添加一个字体路径到字体库.
func AddFontFamily(fontPath ...string) {
fontFamily = append(fontFamily, fontPath...)
}
//ReadFile 读取文件,优先从设置的文件系统中读取,失败后从内置文件系统读取,失败后从磁盘读取.
func ReadFile(name string) ([]byte, error) {
if ioFS != nil {
b, err := fs.ReadFile(ioFS, name)
if err == nil {
return b, nil
}
}
return os.ReadFile(name)
}
func readFontFromFS(fs embed.FS) error {
files, err := fs.ReadDir("fonts")
if err != nil {
log.Printf("解析字体文件失败 -> %+v", err)
return err
} else {
fontFamily = fontFamily[:0]
for _, fi := range files {
if fi.IsDir() { // 忽略目录
continue
}
if strings.HasSuffix(strings.ToLower(fi.Name()), ".ttf") { //匹配文件
fontFamily = append(fontFamily, filepath.Join("fonts", fi.Name()))
}
}
}
return nil
}
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
_ = readFontFromFS(_fs)
}