test: 添加中文水印测试(freetype 直接绘制)

This commit is contained in:
Cai1Cai1 2026-06-30 14:50:23 +08:00
parent c7ff3998ec
commit 25e68c6894

View File

@ -1,13 +1,16 @@
package imglib
import (
"image"
"image/color"
"os"
"testing"
"github.com/fogleman/gg"
"github.com/golang/freetype"
"golang.org/x/image/draw"
)
// TestAddChineseWatermark 给桌面 kbk.png 添加豆包AI风格斜纹平铺水印
// TestAddChineseWatermark 给桌面 kbk.png 添加大号文字水印
func TestAddChineseWatermark(t *testing.T) {
srcPath := `C:\Users\Administrator\Desktop\kbk.png`
@ -17,33 +20,26 @@ func TestAddChineseWatermark(t *testing.T) {
}
bounds := srcImg.Bounds()
dc := gg.NewContext(bounds.Dx(), bounds.Dy())
dc.DrawImage(srcImg, 0, 0)
dst := image.NewRGBA(bounds)
draw.Draw(dst, bounds, srcImg, bounds.Min, draw.Src)
fontPath := getDefaultFontPath()
if fontPath == "" {
t.Skip("未找到中文字体")
font, err := GetFont()
if err != nil {
t.Skipf("获取字体失败: %v", err)
}
if err := dc.LoadFontFace(fontPath, 48); err != nil {
t.Fatalf("加载字体失败: %v", err)
}
c := freetype.NewContext()
c.SetDPI(72)
c.SetFont(font)
c.SetClip(dst.Bounds())
c.SetDst(dst)
// 斜纹平铺水印
tileW, tileH := 500, 400
for y := -tileH; y < bounds.Dy()+tileH; y += tileH {
for x := -tileW; x < bounds.Dx()+tileW; x += tileW {
cx := float64(x) + 250
cy := float64(y) + 200
dc.Push()
dc.RotateAbout(-0.35, cx, cy)
dc.SetRGB(1, 1, 1)
dc.SetAlpha(0.25)
dc.DrawStringAnchored("这是一个水印", cx, cy, 0.5, 0.5)
dc.SetRGBA(1, 1, 1, 0.15)
dc.DrawStringAnchored("这是一个水印", float64(x)+250, float64(y)+200, 0.5, 0.5)
dc.Pop()
}
// 大号红色文字(中间偏上)
c.SetFontSize(120)
c.SetSrc(image.NewUniform(color.RGBA{255, 0, 0, 255}))
pt := freetype.Pt(300, 800)
if _, err := c.DrawString("这是一个水印", pt); err != nil {
t.Fatalf("绘制水印失败: %v", err)
}
outPath := "d:\\source\\daShangDao_utils\\kbk_watermarked.png"
@ -52,7 +48,7 @@ func TestAddChineseWatermark(t *testing.T) {
t.Fatalf("创建文件失败: %v", err)
}
defer f.Close()
err = SavePNG(dc.Image(), outPath)
err = SavePNG(dst, outPath)
if err != nil {
t.Fatalf("保存图片失败: %v", err)
}