注意:如水印文字是中文,需要中文字体
字体下载链接:https://fonts.google.com
package imgUtils
import (
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
"math"
"image"
"image/color"
"image/draw"
"io/ioutil"
"github.com/golang/freetype/truetype"
"github.com/disintegration/imaging"
)
/**
添加文本水印到图片
img:图片数据
watermarkText:水印内容
fontPath:字体路径
angle:旋转角度
*/
func AddWatermark(img image.Image, watermarkText string, fontPath string, angle float64) (image.Image, error) {
// 加载字体
fontBytes, err := ioutil.ReadFile(fontPath)
if err != nil {
return nil, err
}
f, err := truetype.Parse(fontBytes)
if err != nil {
return nil, err
}
// 创建面部字体
face := truetype.NewFace(f, &truetype.Options{
Size: 24,
DPI: 72,
Hinting: font.HintingNone,
})
// 计算文本大小(调整密度)
txtSize := int(math.Ceil(45.0 * 90.0 / 96.0))
// 创建水印图像
bounds := img.Bounds()
wm := image.NewRGBA(bounds)
draw.Draw(wm, bounds, img, bounds.Min, draw.Src)
// 设置字体颜色
col := color.RGBA{R: 0, G: 0, B: 0, A: 20}
// 循环绘制水印
for y := txtSize; y < bounds.Dy(); y += txtSize * 4 {
for x := txtSize; x < bounds.Dx(); x += txtSize * 4 {
// 创建临时图像
temp := image.NewRGBA(image.Rect(0, 0, txtSize*4, txtSize*4))
d := &font.Drawer{
Dst: temp,
Src: image.NewUniform(col),
Face: face,
Dot: fixed.P(0, txtSize),
}
d.DrawString(watermarkText)
// 旋转临时图像
rotated := imaging.Rotate(temp, angle, color.NRGBA{0, 0, 0, 0})
// 绘制旋转后的图像到原始图像
draw.Draw(wm, image.Rect(x, y, x+rotated.Bounds().Dx(), y+rotated.Bounds().Dy()), rotated, image.Point{}, draw.Over)
}
}
return wm, nil
}