当前位置:   article > 正文

【golang】25、图片操作

【golang】25、图片操作

用 “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
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

二、裁剪

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
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/173708
推荐阅读
相关标签
  

闽ICP备14008679号