- 新增 imglib 包,支持 FilePath/URL/Base64 三种图片输入方式 - 纯白占比检测、白底居中合成、等比缩放、去白边、裁切 - 二维码生成与识别、条形码生成(Code128/EAN13/Code39) - 中文文字图片、书籍信息水印、通用水印叠加 - 输出辅助:EncodeToBytes/EncodeToBase64/SaveToFile/SaveJPEG/SavePNG - 字体缓存,避免重复加载 - 完整测试覆盖(23个测试用例)
64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
package imglib
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"runtime"
|
|
"sync"
|
|
|
|
"github.com/golang/freetype/truetype"
|
|
)
|
|
|
|
var (
|
|
fontCacheOnce sync.Once
|
|
cachedFont *truetype.Font
|
|
cachedFontErr error
|
|
)
|
|
|
|
// GetFont 获取系统默认中文字体(全局缓存,仅首次加载时读取磁盘)
|
|
func GetFont() (*truetype.Font, error) {
|
|
fontCacheOnce.Do(func() {
|
|
path := getDefaultFontPath()
|
|
if path == "" {
|
|
cachedFontErr = fmt.Errorf("未找到系统字体文件")
|
|
return
|
|
}
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
cachedFontErr = fmt.Errorf("读取字体文件失败: %v", err)
|
|
return
|
|
}
|
|
cachedFont, cachedFontErr = truetype.Parse(data)
|
|
})
|
|
return cachedFont, cachedFontErr
|
|
}
|
|
|
|
func getDefaultFontPath() string {
|
|
switch runtime.GOOS {
|
|
case "windows":
|
|
paths := []string{
|
|
"C:/Windows/Fonts/simhei.ttf",
|
|
"C:/Windows/Fonts/simsun.ttc",
|
|
"C:/Windows/Fonts/msyh.ttc",
|
|
}
|
|
for _, p := range paths {
|
|
if _, err := os.Stat(p); err == nil {
|
|
return p
|
|
}
|
|
}
|
|
case "darwin":
|
|
return "/System/Library/Fonts/PingFang.ttc"
|
|
case "linux":
|
|
paths := []string{
|
|
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
|
|
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
|
}
|
|
for _, p := range paths {
|
|
if _, err := os.Stat(p); err == nil {
|
|
return p
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|