修复登录及验证码功能

This commit is contained in:
2026-09-03 10:12:30 +08:00
parent 57d9866dab
commit 7c38e84e30
13 changed files with 309 additions and 118 deletions
+12 -6
View File
@@ -1,6 +1,7 @@
package captcha
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
@@ -69,20 +70,23 @@ func drawImage(code string) image.Image {
bg := color.RGBA{240, 245, 255, 255}
draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)
for i := 0; i < 4; i++ {
for i := 0; i < 3; i++ {
x1, _ := rand.Int(rand.Reader, big.NewInt(int64(width)))
y1, _ := rand.Int(rand.Reader, big.NewInt(int64(height)))
x2, _ := rand.Int(rand.Reader, big.NewInt(int64(width)))
y2, _ := rand.Int(rand.Reader, big.NewInt(int64(height)))
drawLine(img, int(x1.Int64()), int(y1.Int64()), int(x2.Int64()), int(y2.Int64()), randomColor())
}
for i := 0; i < 30; i++ {
for i := 0; i < 25; i++ {
x, _ := rand.Int(rand.Reader, big.NewInt(int64(width)))
y, _ := rand.Int(rand.Reader, big.NewInt(int64(height)))
img.Set(int(x.Int64()), int(y.Int64()), randomColor())
}
// 字符居中绘制:字符高 21px (7*3),画布高 40px,垂直居中起始 y 约 9px;4 字符总宽 90px,水平居中起始 x 为 15px
for i, ch := range code {
drawChar(img, 15+i*25, 28, string(ch), randomDarkColor())
offsetY, _ := rand.Int(rand.Reader, big.NewInt(3))
charY := 8 + int(offsetY.Int64()) // 8..10px,垂直完美居中
drawChar(img, 15+i*25, charY, string(ch), randomDarkColor())
}
return img
}
@@ -134,7 +138,7 @@ func drawChar(img *image.RGBA, x, y int, ch string, c color.Color) {
if px == '1' {
for dy := 0; dy < scale; dy++ {
for dx := 0; dx < scale; dx++ {
img.Set(x+col*scale+dx, y-row*scale-7*scale+dy, c)
img.Set(x+col*scale+dx, y+row*scale+dy, c)
}
}
}
@@ -192,7 +196,9 @@ func randomDarkColor() color.RGBA {
}
func encodeToBase64(img image.Image) string {
var buf strings.Builder
png.Encode(base64.NewEncoder(base64.StdEncoding, &buf), img)
var buf bytes.Buffer
enc := base64.NewEncoder(base64.StdEncoding, &buf)
_ = png.Encode(enc, img)
_ = enc.Close()
return buf.String()
}