用 “github.com/fogleman/gg” 可以画线, 框
用 “github.com/disintegration/imaging” 可以变换颜色
一、渲染
1.1 框和字
import "github.com/fogleman/gg"
func DrawRectangles(inPath string, cRects []ColorTextRect, fnImgNameChange FnImgNameChange) (string, error) {
img, err := gg.LoadImage(inPath)
if err != nil {
return "", err
}
dc := gg.NewContextForImage(img)
dc.SetLineWidth(10)
for _, cRect := range cRects {
dc.SetColor(cRect.Color)
dc.DrawRectangle(float64(cRect.Rect.X), float64(cRect.Rect.Y), float64(cRect.Rect.Width), float64(cRect.Rect.Height))
err := dc.LoadFontFace("ch.ttf", 60) // 青鸟华光简美黑.ttf
if err != nil {
log.Errorf("load font face error: %v", err)
}
textX, textY := float64(cRect.Rect.X+15), float64(cRect.Rect.Y+15)
dc.DrawString(cRect.Text, textX, textY)
dc.Stroke()
}
outPath := fnImgNameChange(inPath)
if err := dc.SavePNG(outPath); err != nil {
return "", err
}
return outPath, nil
}
二、裁剪
import "github.com/disintegration/imaging"
func Clip(inPath string, rect entity.Rect, fnImgNameChange FnImgNameChange) (string, error) {
img, err := imaging.Open(inPath)
if err != nil {
return "", err
}
croppedImg := imaging.Crop(img, image.Rect(int(rect.X), int(rect.Y), int(rect.X+rect.Width), int(rect.Y+rect.Height)))
outPath := fnImgNameChange(inPath)
if err := imaging.Save(croppedImg, outPath); err != nil {
return "", err
}
return outPath, nil
}