72 lines
1.3 KiB
Go
72 lines
1.3 KiB
Go
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.BaseCaptcha{
|
|
ExpireIn: captcha.ExpiryDate(expiry)}}
|
|
}
|
|
|
|
func (c *DwellingCaptcha) Image(style string) image.Image {
|
|
isDark := style == "dark"
|
|
ctx := gg.NewContext(dwImageWidth, dwImageHeight)
|
|
|
|
// fill background
|
|
if isDark {
|
|
ctx.SetRGB255(0x0a, 0x0a, 0x0a)
|
|
} else {
|
|
ctx.SetRGB255(0xf5, 0xf5, 0xf5)
|
|
}
|
|
ctx.Clear()
|
|
|
|
// draw text
|
|
if isDark {
|
|
ctx.SetRGB255(0xf5, 0xf5, 0xf5)
|
|
} else {
|
|
ctx.SetRGB255(0x0a, 0x0a, 0x0a)
|
|
}
|
|
ctx.Scale(4.0, 2.7)
|
|
ctx.DrawStringAnchored(string(c.GetAnswer()), 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()
|
|
}
|
|
|
|
return ctx.Image()
|
|
}
|