Easy-Captcha验证码 生成以及校验(简单易懂)

说明

Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目

pom引入

	<dependency>
			<groupId>com.github.whvcse</groupId>
			<artifactId>easy-captcha</artifactId>
			<version>1.6.2</version>
		</dependency>

详解参数类使用

easy-captcha 中提供了下面几种类

类名说明图片
ArithmeticCaptcha数字加减乘除验证在这里插入图片描述
ChineseCaptcha中文验证在这里插入图片描述
ChineseGifCaptcha中文动态验证在这里插入图片描述
GifCaptcha动态字符验证在这里插入图片描述
SpecCaptcha字符验证在这里插入图片描述
CaptchaUtil输出类

源码说明

在上面的类中,都是继承自Captcha类,类中提供了两个主要抽象方法,自定义验证码生成器也需继承Captcha,实现下面两个方法。

   public abstract boolean out(OutputStream var1);

    public abstract String toBase64();

来看SpecCaptcha 默认生成验证码的工具类,其他几种验证码生成类,一样的逻辑。

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.wf.captcha;

import com.wf.captcha.base.Captcha;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;

public class SpecCaptcha extends Captcha {
  //空构造方法
  public SpecCaptcha() {
   }
   //设置验证码的长宽
    public SpecCaptcha(int width, int height) {
        this();
        this.setWidth(width);
        this.setHeight(height);
    }
//设置验证码的长宽,和生成验证码的长度
    public SpecCaptcha(int width, int height, int len) {
        this(width, height);
        this.setLen(len);
    }
//设置验证码的长宽,和生成验证码的长度,以及字体
    public SpecCaptcha(int width, int height, int len, Font font) {
        this(width, height, len);
        this.setFont(font);
    }
  // 验证码返回
    public boolean out(OutputStream out) {
        return this.graphicsImage(this.textChar(), out);
    }
//验证码转为base64
    public String toBase64() {
        return this.toBase64("data:image/png;base64,");
    }

//生成验证码逻辑
    private boolean graphicsImage(char[] strs, OutputStream out) {
        try {
            BufferedImage bi = new BufferedImage(this.width, this.height, 1);
            Graphics2D g2d = (Graphics2D)bi.getGraphics();
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, this.width, this.height);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            this.drawOval(2, g2d);
            g2d.setStroke(new BasicStroke(2.0F, 0, 2));
            this.drawBesselLine(1, g2d);
            g2d.setFont(this.getFont());
            FontMetrics fontMetrics = g2d.getFontMetrics();
            int fW = this.width / strs.length;
            int fSp = (fW - (int)fontMetrics.getStringBounds("W", g2d).getWidth()) / 2;

            for(int i = 0; i < strs.length; ++i) {
                g2d.setColor(this.color());
                int fY = this.height - (this.height - (int)fontMetrics.getStringBounds(String.valueOf(strs[i]), g2d).getHeight() >> 1);
                g2d.drawString(String.valueOf(strs[i]), i * fW + fSp + 3, fY - 3);
            }

            g2d.dispose();
            ImageIO.write(bi, "png", out);
            out.flush();
            boolean var20 = true;
            return var20;
        } catch (IOException var18) {
            var18.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException var17) {
                var17.printStackTrace();
            }

        }

        return false;
    }
}

Captcha使用

以上几种提供的工具类,都有使用测试

package com.test.execption.controller;

import com.ramostear.captcha.HappyCaptcha;
import com.wf.captcha.*;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 类描述:EasyCaptcha 验证码工具
 *
 * @author admin
 * @date 2023-01-02 17:47
 **/

@RestController
@RequestMapping(value = "captcha")
public class EasyCaptchaController {

    /**
     * 生成字符串验证码
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "generatorStr")
    public void generator(HttpServletRequest request, HttpServletResponse response) {
        try {
            CaptchaUtil.out(request, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 生成数字验证码
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "generatorNum")
    public void generatorNum(HttpServletRequest request, HttpServletResponse response) {
        try {
            ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(200, 250);
            arithmeticCaptcha.setLen(2);
            CaptchaUtil.out(arithmeticCaptcha, request, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成中文验证码
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "generatorChinese")
    public void generatorChinese(HttpServletRequest request, HttpServletResponse response) {
        try {
            ChineseCaptcha chineseCaptcha = new ChineseCaptcha(200, 250);
            chineseCaptcha.setLen(2);
            CaptchaUtil.out(chineseCaptcha, request, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成中文动态验证码
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "generatorChineseGif")
    public void generatorChineseGif(HttpServletRequest request, HttpServletResponse response) {
        try {
            ChineseGifCaptcha chineseGifCaptcha = new ChineseGifCaptcha(200, 250);
            chineseGifCaptcha.setLen(2);
            CaptchaUtil.out(chineseGifCaptcha, request, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成字符动态验证码
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "generatorGif")
    public void generatorGif(HttpServletRequest request, HttpServletResponse response) {
        try {
            GifCaptcha captcha = new GifCaptcha(200, 250);
            captcha.setLen(2);
            CaptchaUtil.out(captcha, request, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成字符动态验证码
     * 这个为默认验证码生成器
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "generatorSpec")
    public void generatorSpec(HttpServletRequest request, HttpServletResponse response) {
        try {
            SpecCaptcha captcha = new SpecCaptcha(200, 250);
            captcha.setLen(2);
            CaptchaUtil.out(captcha, request, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }




    /**
     * 验证码校验,并且验证通过后清除,下次不允许再用
     *
     * @param verifyCode
     * @param request
     * @return
     */
    @GetMapping("/verify")
    public String verify(String verifyCode, HttpServletRequest request) {

        Boolean aBoolean = CaptchaUtil.ver(verifyCode, request);
        if (aBoolean) {
            CaptchaUtil.clear(request); //清除验证码
            return "通过";
        }
        return "不通过";
    }

验证图解

使用数字运算验证

生成验证码:
在这里插入图片描述
校验验证码:
结果不对,不通过
在这里插入图片描述
结果正确,通过
在这里插入图片描述

源码测试GitHub

github 测试代码

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
在Django中使用django-simple-captcha生成验证码可以通过以下步骤现: 1. 安装django-simple-captcha库: 在终端中运行以下命令安装django-simple-captcha库: ``` pip install django-simple-captcha ``` 2. 在Django项目的`settings.py`文件中添加`captcha`应用: 打开`settings.py`文件,找到`INSTALLED_APPS`列表,将`'captcha'`添加到其中。 3. 运行数据库迁移: 在终端中运行以下命令,将`captcha`应用的数据库迁移到你的项目中: ``` python manage.py migrate captcha ``` 4. 在需要生成验证码的表单中添加验证码字段: 在你的表单类中导入`CaptchaField`,并将其作为一个字段添加到表单中。例如: ```python from captcha.fields import CaptchaField class MyForm(forms.Form): # 其他字段... captcha = CaptchaField() ``` 5. 在视图函数中验证验证码: 在你的视图函数中,可以通过调用`form.is_valid()`来验证验证码是否正确。例如: ```python def my_view(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): # 验证码正确,执行相应的逻辑 # ... else: # 验证码错误,处理错误信息 # ... else: form = MyForm() return render(request, 'my_template.html', {'form': form}) ``` 6. 在模板中显示验证码输入框: 在你的模板文件中,可以通过`form.captcha`来渲染验证码输入框。例如: ```html <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">提交</button> </form> ``` 这样,你就可以在Django中使用django-simple-captcha生成验证码了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无奈的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值