微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

golang——image库图片上写字

package main

import (
	"github.com/golang/freetype"
	"image"
	"image/color"
	"image/png"
	"io/ioutil"
	"log"
	"os"
)

func main() {
	//图片的宽度
	srcWidth := 200
	//图片的高度
	srcHeight := 200
	imgfile, _ := os.Create("out.png")
	defer imgfile.Close()

	img := image.NewRGBA(image.Rect(0, 0, srcWidth, srcHeight))

	//为背景图片设置颜色
	for y := 0; y < srcWidth; y++ {
		for x := 0; x < srcHeight; x++ {
			img.Set(x, y, color.RGBA{255, 255, 255, 255})
		}
	}

	//读取字体数据  http://fonts.mobanwang.com/201503/12436.html
	fontBytes, err := ioutil.ReadFile("./public/xiawucha.ttf")
	if err != nil {
		log.Println(err)
	}
	//载入字体数据
	font, err := freetype.ParseFont(fontBytes)
	if err != nil {
		log.Println("载入字体失败", err)
	}
	f := freetype.NewContext()
	//设置分辨率
	f.SetDPI(100)
	//设置字体
	f.SetFont(font)
	//设置尺寸
	f.SetFontSize(26)
	f.SetClip(img.Bounds())
	//设置输出的图片
	f.SetDst(img)
	//设置字体颜色(红色)
	f.SetSrc(image.NewUniform(color.RGBA{255, 0, 0, 255}))

	//设置字体的位置
	pt := freetype.Pt(20, 40)

	_, err = f.DrawString("hello,你好", pt)
	if err != nil {
		log.Fatal(err)
	}

	//以png 格式写入文件
	err = png.Encode(imgfile, img)
	if err != nil {
		log.Fatal(err)
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐