75 lines
1.7 KiB
Go
75 lines
1.7 KiB
Go
package captcha
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"image"
|
|
"justcaptcha/pkg/captcha"
|
|
"math/big"
|
|
"time"
|
|
|
|
"github.com/fogleman/gg"
|
|
)
|
|
|
|
const (
|
|
dwImageWidth = 160
|
|
dwImageHeight = 40
|
|
)
|
|
|
|
type DwellingCaptcha struct {
|
|
captcha.Captcha
|
|
}
|
|
|
|
func NewDwellingCaptcha(expiry time.Duration) *DwellingCaptcha {
|
|
return &DwellingCaptcha{
|
|
Captcha: captcha.Captcha{
|
|
ExpireIn: captcha.ExpiryDate(expiry)}}
|
|
}
|
|
|
|
func (c *DwellingCaptcha) generateImage(style string) *image.Image {
|
|
ctx := gg.NewContext(dwImageWidth, dwImageHeight)
|
|
|
|
// fill background
|
|
ctx.SetRGB255(0x0a, 0x0a, 0x0a)
|
|
ctx.Clear()
|
|
|
|
// draw text
|
|
ctx.SetRGB255(0xf5, 0xf5, 0xf5)
|
|
ctx.Scale(4.0, 2.7)
|
|
ctx.DrawStringAnchored(string(c.GetAnswer()), 20, 5, .5, .5)
|
|
|
|
// draw lines and points
|
|
|
|
ctx.SetRGB255(0x9f, 0x2b, 0x68)
|
|
for i := 0; i < 16; i++ {
|
|
x0, _ := rand.Int(rand.Reader, big.NewInt(int64(ctx.Height())))
|
|
x1, _ := rand.Int(rand.Reader, big.NewInt(int64(ctx.Height())))
|
|
r, _ := rand.Int(rand.Reader, big.NewInt(int64(4)))
|
|
ctx.SetLineWidth(2)
|
|
ctx.DrawPoint(float64(x0.Int64()), float64(x1.Int64()), float64(r.Int64()))
|
|
ctx.DrawLine(float64(x0.Int64()), 0, float64(ctx.Height()), float64(x1.Int64()))
|
|
ctx.Stroke()
|
|
}
|
|
|
|
for i := 0; i < 16; i++ {
|
|
x0, _ := rand.Int(rand.Reader, big.NewInt(int64(ctx.Height())))
|
|
x1, _ := rand.Int(rand.Reader, big.NewInt(int64(ctx.Height())))
|
|
r, _ := rand.Int(rand.Reader, big.NewInt(int64(4)))
|
|
ctx.SetLineWidth(2)
|
|
ctx.DrawPoint(float64(x0.Int64()), float64(x1.Int64()), float64(r.Int64()))
|
|
ctx.DrawLine(0, float64(x0.Int64()), float64(x1.Int64()), float64(ctx.Height()))
|
|
ctx.Stroke()
|
|
}
|
|
|
|
c.Image = ctx.Image()
|
|
|
|
return &c.Image
|
|
}
|
|
|
|
func (c *DwellingCaptcha) GetImage(style string) *image.Image {
|
|
if c.Image == nil {
|
|
return c.generateImage(style)
|
|
}
|
|
|
|
return &c.Image
|
|
}
|