Skip to content

Instantly share code, notes, and snippets.

@johnmanjiro13
Last active May 2, 2024 15:22
Show Gist options
  • Save johnmanjiro13/977d35d019790ba304c09dc37144d419 to your computer and use it in GitHub Desktop.
Save johnmanjiro13/977d35d019790ba304c09dc37144d419 to your computer and use it in GitHub Desktop.
Draw text to image in Go
package main
import (
"bufio"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"log"
"os"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
_ "embed"
_ "image/png"
)
var (
//go:embed fonts/Aileron-Regular.otf
fontBytes []byte
)
func main() {
file, err := os.Open("source.png")
if err != nil {
log.Fatalf("failed to open file: %v", err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
log.Fatalf("failed to decode image: %v", err)
}
dst := image.NewRGBA(img.Bounds())
draw.Draw(dst, dst.Bounds(), img, image.Point{}, draw.Src)
f, err := opentype.Parse(fontBytes)
if err != nil {
log.Fatalf("failed to parse font: %v", err)
}
face, err := opentype.NewFace(f, &opentype.FaceOptions{
Size: float64(img.Bounds().Dx() / 5),
DPI: 72,
Hinting: font.HintingNone,
})
if err != nil {
log.Fatalf("failed to create new face: %v", err)
}
d := &font.Drawer{
Dst: dst,
Src: image.NewUniform(color.RGBA{255, 255, 255, 255}),
Face: face,
Dot: fixed.Point26_6{fixed.Int26_6(img.Bounds().Dx() / 11 * 3 * 64), fixed.Int26_6(img.Bounds().Dy() / 5 * 3 * 64)},
}
d.DrawString("LGTM")
newFile, err := os.Create("out.jpg")
if err != nil {
log.Fatalf("failed to create file: %v", err)
}
defer newFile.Close()
b := bufio.NewWriter(newFile)
if err := jpeg.Encode(b, dst, &jpeg.Options{Quality: 100}); err != nil {
log.Fatalf("failed to encode image: %v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment