Skip to content

Instantly share code, notes, and snippets.

@tomowarkar
Last active December 11, 2019 12:08
Show Gist options
  • Save tomowarkar/43955834693cb737a2c8818a44347b41 to your computer and use it in GitHub Desktop.
Save tomowarkar/43955834693cb737a2c8818a44347b41 to your computer and use it in GitHub Desktop.
文字列を画像化
package main
import (
"bytes"
"fmt"
"image"
"image/png"
"os"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/font/gofont/gobold"
"golang.org/x/image/math/fixed"
"golang.org/x/xerrors"
)
func main() {
err := run("Hooooooo!")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(text string) error {
// TODO: 日本語対応
// TODO: テキストのながさを元に動的にサイズ決定ができたら嬉しい
fontSize := 80.0
imageWidth, imageHeight, textTopMargin := 640, 400, 220
if len(text) > 12 {
return xerrors.New("text length should less 12")
}
ft, err := truetype.Parse(gobold.TTF)
if err != nil {
return err
}
opt := truetype.Options{
Size: fontSize,
DPI: 0,
Hinting: 0,
GlyphCacheEntries: 0,
SubPixelsX: 0,
SubPixelsY: 0,
}
img := image.NewRGBA(image.Rect(0, 0, imageWidth, imageHeight))
face := truetype.NewFace(ft, &opt)
dr := &font.Drawer{
Dst: img,
Src: image.White,
Face: face,
Dot: fixed.Point26_6{},
}
dr.Dot.X = (fixed.I(imageWidth) - dr.MeasureString(text)) / 2
dr.Dot.Y = fixed.I(textTopMargin)
dr.DrawString(text)
buf := &bytes.Buffer{}
err = png.Encode(buf, img)
if err != nil {
return err
}
f, err := os.Create("./img/hoge.png")
if err != nil {
return err
}
defer f.Close()
f.Write(buf.Bytes())
return nil
}
// https://qiita.com/uobikiemukot/items/11dac0f1418492493226
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment