头图

GoCaptcha 是行为式验证码,支持文本/图形点选、滑动/拖拽、旋转等验证模式,并提供 Golang 生成和前端 JavaScript/Vue/React/Angular/Solid/Svelte 等依赖库。

快速使用

package main

import (
    "encoding/json"
    "fmt"
    "image"
    "log"
    "io/ioutil"

    "github.com/golang/freetype"
    "github.com/golang/freetype/truetype"
    "github.com/wenlng/go-captcha/v2/base/option"
    "github.com/wenlng/go-captcha/v2/click"
    "github.com/wenlng/go-captcha/v2/base/codec"
)

var textCapt click.Captcha

func init() {
    builder := click.NewBuilder(
        click.WithRangeLen(option.RangeVal{Min: 4, Max: 6}),
        click.WithRangeVerifyLen(option.RangeVal{Min: 2, Max: 4}),
    )

    // 可以使用预置的素材资源:https://github.com/wenlng/go-captcha-assets
    fontN, err := loadFont("../resources/fzshengsksjw_cu.ttf")
    if err != nil {
        log.Fatalln(err)
    }

    bgImage, err := loadPng("../resources/bg.png")
    if err != nil {
        log.Fatalln(err)
    }

    builder.SetResources(
        click.WithChars([]string{"这", "是", "随", "机", "的", "文", "本", "种", "子", "呀"}),
        click.WithFonts([]*truetype.Font{
            fontN,
        }),
        click.WithBackgrounds([]image.Image{
            bgImage,
        }),
    )

    textCapt = builder.Make()
}

func loadPng(p string) (image.Image, error) {
    imgBytes, err := ioutil.ReadFile(p)
    if err != nil {
        return nil, err
    }
    return codec.DecodeByteToPng(imgBytes)
}

func loadFont(p string) (*truetype.Font, error) {
    fontBytes, err := ioutil.ReadFile(p)
    if err != nil {
        panic(err)
    }
    return freetype.ParseFont(fontBytes)
}


func main() {
    captData, err := textCapt.Generate()
    if err != nil {
        log.Fatalln(err)
    }

    dotData := captData.GetData()
    if dotData == nil {
        log.Fatalln(">>>>> generate err")
    }

    dots, _ := json.Marshal(dotData)
    fmt.Println(">>>>> ", string(dots))

    var mBase64, tBase64 string
    mBase64, err = captData.GetMasterImage().ToBase64()
    if err != nil {
        fmt.Println(err)
    }
    tBase64, err = captData.GetThumbImage().ToBase64()
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(">>>>> ", mBase64)
    fmt.Println(">>>>> ", tBase64)
    
    //err = captData.GetMasterImage().SaveToFile("../resources/master.jpg", option.QualityNone)
    //if err != nil {
    //    fmt.Println(err)
    //}
    //err = captData.GetThumbImage().SaveToFile("../resources/thumb.png")
    //if err != nil {
    //    fmt.Println(err)
    //}
}

谦和的荔枝
1 声望0 粉丝