95 lines
2.4 KiB
Go
95 lines
2.4 KiB
Go
package image
|
|
|
|
import (
|
|
"fmt"
|
|
"image"
|
|
"image/color"
|
|
"image/png"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"github.com/golang/freetype"
|
|
"github.com/golang/freetype/truetype"
|
|
|
|
"douyu_go/internal/constants"
|
|
"douyu_go/internal/logger"
|
|
"douyu_go/internal/types"
|
|
"douyu_go/internal/utils"
|
|
)
|
|
|
|
// SaveSuccessImage 保存成功兑换结果图片。
|
|
func SaveSuccessImage(account types.Account, product types.Product, roleName string, font *truetype.Font, successDir string) {
|
|
if font == nil {
|
|
return
|
|
}
|
|
if successDir == "" {
|
|
successDir = constants.DefaultSuccessDir
|
|
}
|
|
if err := os.MkdirAll(successDir, 0755); err != nil {
|
|
logger.LogEvent("图片", "error", "成功图片目录创建失败: %v", err)
|
|
return
|
|
}
|
|
|
|
productName := product.CommodityName
|
|
if productName == "" {
|
|
productName = product.CommodityID
|
|
}
|
|
now := time.Now().In(constants.CST)
|
|
|
|
width, height := 600, 280
|
|
img := image.NewRGBA(image.Rect(0, 0, width, height))
|
|
bgColor := color.RGBA{213, 239, 253, 255}
|
|
topColor := color.RGBA{76, 175, 80, 255}
|
|
white := color.RGBA{255, 255, 255, 255}
|
|
black := color.RGBA{0, 0, 0, 255}
|
|
|
|
for x := 0; x < width; x++ {
|
|
for y := 0; y < height; y++ {
|
|
if y < 60 {
|
|
img.Set(x, y, topColor)
|
|
} else {
|
|
img.Set(x, y, bgColor)
|
|
}
|
|
}
|
|
}
|
|
|
|
ctx := freetype.NewContext()
|
|
ctx.SetDPI(72)
|
|
ctx.SetFont(font)
|
|
ctx.SetClip(img.Bounds())
|
|
ctx.SetDst(img)
|
|
|
|
lines := []struct {
|
|
Text string
|
|
Size float64
|
|
X, Y int
|
|
Color color.Color
|
|
}{
|
|
{productName, 20, 25, 42, white},
|
|
{"兑换时间:" + now.Format("2006年01月02日 15:04:05"), 16, 25, 110, black},
|
|
{"游戏昵称:" + utils.EmptyDefault(roleName, "未知"), 16, 25, 150, black},
|
|
{"兑换账号:" + account.Name, 16, 25, 190, black},
|
|
}
|
|
for _, line := range lines {
|
|
ctx.SetFontSize(line.Size)
|
|
ctx.SetSrc(image.NewUniform(line.Color))
|
|
_, _ = ctx.DrawString(line.Text, freetype.Pt(line.X, line.Y))
|
|
}
|
|
|
|
ownerName := utils.EmptyDefault(roleName, account.Name)
|
|
name := utils.SafeFilename(fmt.Sprintf("%s_%s_%s.png", ownerName, productName, now.Format("20060102_150405.000")))
|
|
path := filepath.Join(successDir, name)
|
|
file, err := os.Create(path)
|
|
if err != nil {
|
|
logger.LogEvent("图片", "error", "成功图片创建失败: %v", err)
|
|
return
|
|
}
|
|
defer file.Close()
|
|
if err := png.Encode(file, img); err != nil {
|
|
logger.LogEvent("图片", "error", "成功图片保存失败: %v", err)
|
|
return
|
|
}
|
|
logger.LogEvent("图片", "success", "成功图片已保存: %s", path)
|
|
}
|