前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang——image库图片上写字

golang——image库图片上写字

作者头像
码缘
发布2021-04-28 11:18:15
2.2K1
发布2021-04-28 11:18:15
举报
文章被收录于专栏:PHP修行之路PHP修行之路
代码语言:javascript
复制
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)
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-04-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档