Skip to content

Instantly share code, notes, and snippets.

@liuguangw
Last active August 18, 2022 14:17
Show Gist options
  • Save liuguangw/5217535afcabca89edaee84e97872382 to your computer and use it in GitHub Desktop.
Save liuguangw/5217535afcabca89edaee84e97872382 to your computer and use it in GitHub Desktop.
用go语言创建图片,并在图片上写汉字
package main
import (
_ "embed"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"golang.org/x/image/math/fixed"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
//go:embed SourceHanSansCN-Normal.ttf
var myFont []byte
func main() {
img := image.NewRGBA(image.Rect(0, 0, 320, 100))
bg := color.RGBA{255, 255, 255, 255}
red := color.RGBA{255, 0, 0, 255}
draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)
font, err := truetype.Parse(myFont)
if err != nil {
panic(err)
}
ctx := freetype.NewContext()
ctx.SetClip(img.Bounds())
ctx.SetSrc(&image.Uniform{red})
ctx.SetDst(img)
ctx.SetFont(font)
ctx.SetFontSize(80.0)
if _, err := ctx.DrawString("你好世界", fixed.P(0, 80)); err != nil {
panic(err)
}
f, err := os.Create("draw.png")
if err != nil {
panic(err)
}
defer f.Close()
png.Encode(f, img)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment