justcaptcha/internal/captcha/dwelling_captcha.go

72 lines
1.3 KiB
Go
Raw Normal View History

package captcha
import (
"image"
"justcaptcha/pkg/captcha"
"math/rand"
"time"
"github.com/fogleman/gg"
)
const (
dwImageWidth = 160
dwImageHeight = 40
)
type DwellingCaptcha struct {
captcha.BaseCaptcha
}
func NewDwellingCaptcha(expiry time.Duration) *DwellingCaptcha {
return &DwellingCaptcha{
BaseCaptcha: *captcha.NewBaseCaptcha(expiry)}
}
func (c *DwellingCaptcha) Image(style string) *image.Image {
2022-06-27 03:03:22 +04:00
isDark := style == "dark"
ctx := gg.NewContext(dwImageWidth, dwImageHeight)
// fill background
2022-06-27 03:03:22 +04:00
if isDark {
ctx.SetRGB255(0x0a, 0x0a, 0x0a)
} else {
ctx.SetRGB255(0xf5, 0xf5, 0xf5)
}
ctx.Clear()
// draw text
2022-06-27 03:03:22 +04:00
if isDark {
ctx.SetRGB255(0xf5, 0xf5, 0xf5)
} else {
ctx.SetRGB255(0x0a, 0x0a, 0x0a)
}
ctx.Scale(4.0, 2.7)
ctx.DrawStringAnchored(string(c.Answer()), 20, 5, .5, .5)
// draw lines and points
h := float64(ctx.Height())
for i := 0; i < 24; i++ {
x0 := rand.Float64() * h
x1 := rand.Float64() * h
x2 := rand.Float64() * h
x3 := rand.Float64() * h
ctx.DrawLine(x0, 0, h, x1)
ctx.DrawLine(0, x2, x3, h)
r := rand.Intn(256)
g := rand.Intn(256)
b := rand.Intn(256)
ctx.SetRGB255(r, g, b)
lw := float64(rand.Float32() * 4.0)
if lw == 0 {
lw = 0.1
}
ctx.SetLineWidth(lw)
ctx.Stroke()
}
i := ctx.Image()
return &i
}