Skip to content

Instantly share code, notes, and snippets.

@rodolfoag
Last active July 18, 2021 20:03
Show Gist options
  • Save rodolfoag/c644cf9ca2bc853442d8fd7cd68c9872 to your computer and use it in GitHub Desktop.
Save rodolfoag/c644cf9ca2bc853442d8fd7cd68c9872 to your computer and use it in GitHub Desktop.
Add text to image in go
package main
import (
"encoding/csv"
"fmt"
"os"
"strings"
"github.com/fogleman/gg"
)
func main() {
names, err := importCSV("./lista-rodolfo.csv")
if err != nil {
panic(err)
}
for _, v := range names {
fmt.Printf("Gerando convite para: %s\n", v)
if err := saveInvite(v); err != nil {
panic(err)
}
}
}
func saveInvite(text string) error {
const WIDTH = 1417
const HEIGHT = 2000
// const FONT = "./fonts/Open_Sans/OpenSans-Regular.ttf"
// const FONT = "./fonts/Cinzel/static/Cinzel-Medium.ttf"
const FONT = "./fonts/Montserrat/Montserrat-Regular.ttf"
im, err := gg.LoadImage("src.png")
if err != nil {
return err
}
dc := gg.NewContext(WIDTH, HEIGHT)
dc.SetRGB(1, 1, 1)
dc.Clear()
dc.SetRGB(0.45, 0.45, 0.45)
if err := dc.LoadFontFace(FONT, 50); err != nil {
return err
}
// dc.DrawStringAnchored(strings.ToUpper(text), WIDTH/2, 276, 0.5, 0.5)
dc.DrawRoundedRectangle(0, 0, 512, 512, 0)
dc.DrawImage(im, 0, 0)
dc.DrawStringAnchored("PARA "+strings.ToUpper(text), WIDTH/2, 276, 0.5, 0.5)
dc.Clip()
fname := strings.ReplaceAll(text, " ", "_")
// remove special chars
// re, err := regexp.Compile(`[^\w]`)
// if err != nil {
// log.Fatal(err)
// }
return dc.SavePNG(fmt.Sprintf("./out/%s.png", fname))
}
func importCSV(path string) ([]string, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
lines, err := csv.NewReader(f).ReadAll()
if err != nil {
return nil, err
}
var ret []string
for _, l := range lines {
ret = append(ret, l[0])
}
return ret, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment