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"
|
2022-12-06 02:04:05 +03:00
|
|
|
database "nefrace.ru/doomer/db"
|
2022-12-04 17:30:08 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type Doomer struct {
|
|
|
|
Face font.Face
|
2022-12-06 02:04:05 +03:00
|
|
|
db *database.Db
|
2022-12-04 17:30:08 +03:00
|
|
|
Border int
|
|
|
|
}
|
|
|
|
|
2022-12-06 02:04:05 +03:00
|
|
|
func NewDoomer(db *database.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)
|
2022-12-06 02:04:05 +03:00
|
|
|
store := d.db.Prefix(database.ImageItem)
|
2022-12-06 00:57:09 +03:00
|
|
|
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
|
|
|
|
}
|