v语言 实现图形验证码

How to use V to write a graphic captcha?

import rand
import time
import encoding.base64

struct Captcha {
mut:
    text  string
    image string // Base64编码的SVG图像
}

// 生成图形验证码
pub fn generate_captcha() Captcha {
    width := 150
    height := 50
    char_count := 5 // 验证码字符数量

    // 1. 生成随机文本
    chars := 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' // 排除易混淆字符
    mut text := ''
    for _ in 0 .. char_count {
        idx := rand.intn(chars.len) or { 0 }
        text += chars[idx..idx + 1]
    }

    // 2. 创建SVG图像
    mut svg := '<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0,0,${width},${height}">\n'

    // 背景(渐变)
    svg += '<defs><linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stop-color="#f8f9fa" />
              <stop offset="100%" stop-color="#e9ecef" />
            </linearGradient></defs>
            <rect width="100%" height="100%" fill="url(#bg)" />\n'

    // 干扰线
    for _ in 0 .. 5 {
        x1 := rand.intn(width) or { 0 }
        y1 := rand.intn(height) or { 0 }
        x2 := rand.intn(width) or { 0 }
        y2 := rand.intn(height) or { 0 }
        stroke := match rand.intn(3) or { 0 } {
            0 { '#adb5bd' }
            1 { '#ced4da' }
            else { '#dee2e6' }
        }
        svg += '<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${stroke}" stroke-width="1" />\n'
    }

    // 噪点
    for _ in 0 .. 50 {
        x := rand.intn(width) or { 0 }
        y := rand.intn(height) or { 0 }
        svg += '<circle cx="${x}" cy="${y}" r="1" fill="#495057" />\n'
    }

    // 验证码文本(带随机变换)
    font_size := 24
    for i in 0 .. text.len {
        ch := text[i..i + 1]
        x := 25 + i * 30 + rand.intn(10) or { 0 } - 5
        y := 35 + rand.intn(10) or { 0 } - 5
        rotate := rand.intn(30) or { 0 } - 15

        // 随机颜色(深色系)
        fill := match rand.intn(5) or { 0 } {
            0 { '#212529' }
            1 { '#343a40' }
            2 { '#495057' }
            3 { '#6c757d' }
            else { '#343a40' }
        }

        svg += '<text x="${x}" y="${y}" font-family="Arial" font-size="${font_size}"
                fill="${fill}" transform="rotate(${rotate},${x},${y})"
                font-weight="bold">${ch}</text>\n'
    }

    svg += '</svg>'

    // 3. 返回Base64编码的SVG
    return Captcha{
        text:  text
        image: base64_encode(svg)
    }
}

// Base64编码
fn base64_encode(s string) string {
    return 'data:image/svg+xml;base64,' + base64.encode_str(s)
}

// 示例使用
fn main() {
    // 设置随机种子
    now := time.now()
    rand.seed([u32(now.unix()), u32(now.nanosecond)])

    // 生成验证码
    captcha := generate_captcha()
    dump(captcha.image)
    println('验证码文本: ${captcha.text}')
    println('图像数据: ${captcha.image[..50]}...') // 打印部分Base64数据
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容