94 lines
1.9 KiB
Go
94 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"image/color"
|
|
"image/png"
|
|
|
|
"github.com/fogleman/gg"
|
|
"golang.org/x/image/font"
|
|
)
|
|
|
|
type BackgroundType int
|
|
|
|
const (
|
|
Transparent BackgroundType = iota
|
|
White
|
|
Black
|
|
Gradient
|
|
)
|
|
|
|
type Image struct {
|
|
ctx *gg.Context
|
|
face font.Face
|
|
bgType BackgroundType
|
|
fgColor color.Color
|
|
}
|
|
|
|
func NewImage(ctx *gg.Context, bgType BackgroundType, face font.Face) Image {
|
|
fgColor := color.Black
|
|
if bgType == Transparent || bgType == Black || bgType == Gradient {
|
|
fgColor = color.White
|
|
}
|
|
return Image{
|
|
ctx: ctx,
|
|
bgType: bgType,
|
|
fgColor: fgColor,
|
|
face: face,
|
|
}
|
|
}
|
|
|
|
func (img *Image) GenText(text string) {
|
|
img.MakeBackground()
|
|
img.Print(text)
|
|
}
|
|
|
|
func (img *Image) ToBytes() (*[]byte, error) {
|
|
buff := new(bytes.Buffer)
|
|
err := png.Encode(buff, img.ctx.Image())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
b := buff.Bytes()
|
|
return &b, nil
|
|
}
|
|
|
|
func (img *Image) MakeBackground() {
|
|
if img.bgType == Transparent {
|
|
return
|
|
}
|
|
if img.bgType == Gradient {
|
|
img.fillGradient()
|
|
} else {
|
|
img.fillBG()
|
|
}
|
|
}
|
|
|
|
func (img *Image) Print(text string) {
|
|
imgW, imgH := img.ctx.Width(), img.ctx.Height()
|
|
img.ctx.SetColor(img.fgColor)
|
|
img.ctx.SetFontFace(img.face)
|
|
img.ctx.DrawStringWrapped(text, float64(imgW)/2, float64(imgH)/2, 0.5, 0.5, 600, 1, gg.AlignCenter)
|
|
}
|
|
|
|
func (img *Image) fillGradient() {
|
|
imgW, imgH := img.ctx.Width(), img.ctx.Height()
|
|
grad := gg.NewLinearGradient(0, 0, 0, float64(imgH))
|
|
grad.AddColorStop(0, color.RGBA{200, 50, 50, 255})
|
|
grad.AddColorStop(1, color.RGBA{20, 0, 0, 255})
|
|
img.ctx.SetFillStyle(grad)
|
|
img.ctx.DrawRectangle(0, 0, float64(imgW), float64(imgH))
|
|
img.ctx.Fill()
|
|
}
|
|
|
|
func (img *Image) fillBG() {
|
|
col := color.White
|
|
if img.bgType == Black {
|
|
col = color.Black
|
|
}
|
|
imgW, imgH := img.ctx.Width(), img.ctx.Height()
|
|
img.ctx.SetFillStyle(gg.NewSolidPattern(col))
|
|
img.ctx.DrawRectangle(0, 0, float64(imgW), float64(imgH))
|
|
img.ctx.Fill()
|
|
}
|