go 将文字和图片合成

将收到的文字与图片合成


import (
	"candymachine/model"
	"fmt"
	"image"
	"image/color"
	"image/draw"
	"image/gif"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"net/http"
	"os"

	log "github.com/sirupsen/logrus"

	"github.com/golang/freetype"
	"github.com/golang/freetype/truetype"
	"golang.org/x/image/font"
)

// TextBrush 字体相关
type TextBrush struct {
	FontType  *truetype.Font
	FontSize  float64
	FontColor *image.Uniform
	TextWidth int
}

func NewTextBrush(FontFilePath string, FontSize float64, FontColor *image.Uniform, textWidth int) (*TextBrush, error) {
	fontFile, err := ioutil.ReadFile(FontFilePath)
	if err != nil {
		return nil, err
	}
	fontType, err := truetype.Parse(fontFile)
	if err != nil {
		return nil, err
	}
	if textWidth <= 0 {
		textWidth = 20
	}
	return &TextBrush{FontType: fontType, FontSize: FontSize, FontColor: FontColor, TextWidth: textWidth}, nil
}

// DrawFontOnRGBA 图片插入文字
func (fb *TextBrush) DrawFontOnRGBA(rgba *image.RGBA, pt image.Point, content string) error {

	c := freetype.NewContext()
	c.SetDPI(72)
	c.SetFont(fb.FontType)
	c.SetHinting(font.HintingFull)
	c.SetFontSize(fb.FontSize)
	c.SetClip(rgba.Bounds())
	c.SetDst(rgba)
	c.SetSrc(fb.FontColor)

	_, err := c.DrawString(content, freetype.Pt(pt.X, pt.Y))
	if err != nil {
		return err
	}

	return nil
}

func Image2RGBA(img image.Image) *image.RGBA {

	baseSrcBounds := img.Bounds().Max

	newWidth := baseSrcBounds.X
	newHeight := baseSrcBounds.Y

	des := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight)) // 底板
	//首先将一个图片信息存入jpg
	draw.Draw(des, des.Bounds(), img, img.Bounds().Min, draw.Over)

	return des
}

func GetImageFromFile(filePath string) (img image.Image, err error) {
	f1Src, err := os.Open(filePath)

	if err != nil {
		return nil, err
	}
	defer f1Src.Close()

	buff := make([]byte, 512) // why 512 bytes ? see http://golang.org/pkg/net/http/#DetectContentType
	_, err = f1Src.Read(buff)

	if err != nil {
		return nil, err
	}

	filetype := http.DetectContentType(buff)

	fSrc, err := os.Open(filePath)
	defer fSrc.Close()

	switch filetype {
	case "image/jpeg", "image/jpg":
		img, err = jpeg.Decode(fSrc)
		if err != nil {
			fmt.Println("jpeg error")
			return nil, err
		}

	case "image/gif":
		img, err = gif.Decode(fSrc)
		if err != nil {
			return nil, err
		}

	case "image/png":
		img, err = png.Decode(fSrc)
		if err != nil {
			return nil, err
		}
	default:
		return nil, err
	}
	return img, nil
}

func SaveImage(targetPath string, m image.Image) error {
	fSave, err := os.Create(targetPath)
	if err != nil {
		return err
	}
	defer fSave.Close()

	err = jpeg.Encode(fSave, m, nil)

	if err != nil {
		return err
	}

	return nil
}

func StrIntoImg(font model.OrderImage, rgb map[int]byte) error {
	var textBrush *TextBrush
	var err error
	switch font.FontStyle {
	case "default":
		textBrush, err = NewTextBrush("./static/font/default.ttf", font.FontSize, image.Black, 20)
		if err != nil {
			log.Error(err)
			return err
		}
	case "bold":
		textBrush, err = NewTextBrush("./static/font/bold.ttf", font.FontSize, image.Black, 20)
		if err != nil {
			log.Error(err)
			return err
		}
	case "italic":
		textBrush, err = NewTextBrush("./static/font/italic.ttf", font.FontSize, image.Black, 20)
		if err != nil {
			log.Error(err)
			return err
		}
	case "bold_italic":
		textBrush, err = NewTextBrush("./static/font/bold_italic.ttf", font.FontSize, image.Black, 20)
		if err != nil {
			log.Error(err)
			return err
		}
	default:
		textBrush, err = NewTextBrush("./static/font/default.ttf", 20, image.Black, 20)
		if err != nil {
			log.Error(err)
			return err
		}
	}

	background, err := GetImageFromFile(fmt.Sprintf("./static/image/%d.jpg", font.Pid))
	if err != nil {
		log.Error("获取图片底板失败", err)
		return err
	}

	des := Image2RGBA(background)

	//调整颜色
	textBrush.FontColor = image.NewUniform(color.RGBA{
		R: rgb[0],
		G: rgb[1],
		B: rgb[2],
		A: 255,
	})

	err = textBrush.DrawFontOnRGBA(des, image.Pt(30, 50), font.Content)
	if err != nil {
		log.Error("图片插入文字失败")
		return err
	}

	if err := SaveImage(fmt.Sprintf("./static/merge/%d-m.jpg", font.Pid), des); err != nil {
		log.Error("strIntoImg生成失败", err)
		return err
	}

	return nil
}

字体网上下载就可以,需要ttf格式,名字自定义。

结构体OrderImage 成员为id,字体尺寸,字体风格等。跟英文对照一下就可以

RGB通过一个小工具(放在下面了)将字符串转为16进制,例如前端所传RGB"F6A188”(#号需要截掉,也可以传过来后端自己截取) 

import (
	"encoding/hex"
)

func Str2Hex(strData string) map[int]byte {

	rgb := make(map[int]byte)
	// 将HEX编码的字符串转换为HEX数据
	data, _ := hex.DecodeString(strData)
	for index := 0; index < 3; index++ {
		rgb[index] = data[index]
	}

	return rgb

}

参考于go如何实现图片拼接,文字书写 | 码农家园 (codenong.com)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值