qq_bot/service/xibao/image_gen.go
2024-10-11 00:14:11 +08:00

57 lines
1.4 KiB
Go

package xibao
import (
"log"
"strings"
"github.com/fogleman/gg"
)
func GenerateCongratulationImage(text string, inputFile, outputFile string, isGood bool) {
// 加载喜报背景图片
im, err := gg.LoadImage(inputFile) // 需要提前准备的背景图片
if err != nil {
log.Print("无法加载喜报图片:", err)
return
}
// 创建与背景图片大小相同的画布
width := im.Bounds().Dx()
height := im.Bounds().Dy()
dc := gg.NewContext(width, height)
// 将背景图片绘制到画布上
dc.DrawImage(im, 0, 0)
// 设置字体和大小,字体文件需要自备,放在合适的路径
if err := dc.LoadFontFace("./resource/font.ttf", 96); err != nil {
log.Print("无法加载字体:", err)
return
}
if isGood {
// 设置文本颜色为红色
dc.SetRGB(1, 0.1, 0.1)
} else {
dc.SetRGB(0.1, 0.1, 1)
}
// 将文本按 \n 分割为多行
lines := strings.Split(text, "\n")
// 设置初始绘制的 y 位置,可以根据需要调整
startY := float64(height) / 2
lineHeight := 120.0 // 行高,可以根据字体大小调整
// 居中绘制每一行
for i, line := range lines {
x := float64(width) / 2
y := startY + float64(i)*lineHeight
dc.DrawStringAnchored(line, x, y, 0.5, 0.5)
}
// 将生成的图片保存为输出文件
err = dc.SavePNG(outputFile)
if err != nil {
log.Print("无法保存生成的图片:", err)
}
}