Better CAPTCHA image generation algorithm.

This commit is contained in:
Alexander Andreev 2022-06-27 20:48:39 +04:00
parent 21e5ec118e
commit a31c995909
Signed by: Arav
GPG Key ID: 0388CC8FAA51063F

View File

@ -1,10 +1,9 @@
package captcha package captcha
import ( import (
"crypto/rand"
"image" "image"
"justcaptcha/pkg/captcha" "justcaptcha/pkg/captcha"
"math/big" "math/rand"
"time" "time"
"github.com/fogleman/gg" "github.com/fogleman/gg"
@ -47,30 +46,28 @@ func (c *DwellingCaptcha) generateImage(style string) *image.Image {
ctx.DrawStringAnchored(string(c.GetAnswer()), 20, 5, .5, .5) ctx.DrawStringAnchored(string(c.GetAnswer()), 20, 5, .5, .5)
// draw lines and points // draw lines and points
h := float64(ctx.Height())
ctx.SetRGB255(0x9f, 0x2b, 0x68) for i := 0; i < 24; i++ {
for i := 0; i < 16; i++ { x0 := rand.Float64() * h
x0, _ := rand.Int(rand.Reader, big.NewInt(int64(ctx.Height()))) x1 := rand.Float64() * h
x1, _ := rand.Int(rand.Reader, big.NewInt(int64(ctx.Height()))) x2 := rand.Float64() * h
r, _ := rand.Int(rand.Reader, big.NewInt(int64(4))) x3 := rand.Float64() * h
ctx.SetLineWidth(2) ctx.DrawLine(x0, 0, h, x1)
ctx.DrawPoint(float64(x0.Int64()), float64(x1.Int64()), float64(r.Int64())) ctx.DrawLine(0, x2, x3, h)
ctx.DrawLine(float64(x0.Int64()), 0, float64(ctx.Height()), float64(x1.Int64())) r := rand.Intn(256)
ctx.Stroke() 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)
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() ctx.Stroke()
} }
c.Image = ctx.Image() c.Image = ctx.Image()
return &c.Image return &c.Image
} }