package main import ( "fmt" "log" "strings" "github.com/fogleman/gg" "golang.org/x/image/font" ) type Doomer struct { Face font.Face db *Db Border int } func NewDoomer(db *Db) *Doomer { face, err := gg.LoadFontFace("./fonts/AmazDooMLeft.ttf", 108) if err != nil { log.Fatalf("Error loading font: %v", err) } return &Doomer{ Face: face, Border: 12, db: db, } } func (d *Doomer) GetImage(text string, bgType BackgroundType) (*[]byte, error) { hashed := hash(text) key := hashed + ":" + fmt.Sprint(bgType) store := d.db.Prefix(ImageItem) img, err := store.GetItem(key) if err != nil { image, err := d.GenImage(text, bgType) if err != nil { return nil, err } store.StoreItem(key, *image) img = *image } return &img, nil } func (d *Doomer) GenImage(text string, bgType BackgroundType) (*[]byte, error) { textW, textH := d.measureText(text) imgW, imgH := int(textW)+d.Border*2, int(textH)+d.Border*2 ctx := gg.NewContext(imgW, imgH) img := NewImage(ctx, bgType, d.Face) img.GenText(text) return img.ToBytes() } func (d *Doomer) measureText(text string) (float64, float64) { textctx := gg.NewContext(1, 1) textctx.SetFontFace(d.Face) textWrapped := textctx.WordWrap(text, 600) textW, textH := textctx.MeasureMultilineString(strings.Join(textWrapped, "\n"), 1) return textW, textH }