doomer/doomer.go

63 lines
1.3 KiB
Go
Raw Normal View History

2022-12-04 17:30:08 +03:00
package main
import (
2022-12-06 00:57:09 +03:00
"fmt"
2022-12-04 17:30:08 +03:00
"log"
"strings"
"github.com/fogleman/gg"
"golang.org/x/image/font"
)
type Doomer struct {
Face font.Face
2022-12-06 00:57:09 +03:00
db *Db
2022-12-04 17:30:08 +03:00
Border int
}
2022-12-06 00:57:09 +03:00
func NewDoomer(db *Db) *Doomer {
2022-12-04 17:30:08 +03:00
face, err := gg.LoadFontFace("./fonts/AmazDooMLeft.ttf", 108)
if err != nil {
log.Fatalf("Error loading font: %v", err)
}
return &Doomer{
Face: face,
Border: 12,
2022-12-06 00:57:09 +03:00
db: db,
2022-12-04 17:30:08 +03:00
}
}
2022-12-06 00:57:09 +03:00
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
}
2022-12-04 17:30:08 +03:00
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
}