第三节 使用谷歌kaptcha生成验证码

亮子 2022-06-23 14:22:26 17186 0 0 0

1、添加依赖

<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

2、工具类

package com.shenmazong.utils;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2022/1/12 13:02
 */

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

//依赖
//<dependency>
//<groupId>com.github.penggle</groupId>
//<artifactId>kaptcha</artifactId>
//<version>2.3.2</version>
//</dependency>

/**
 * @author 军哥
 * @version 1.0
 * @description: 图形验证码
 * @date 2022/1/6 19:08
 */

public class VerifyCodeUtil {
    private DefaultKaptcha defaultKaptcha;
    private Properties properties;

    public VerifyCodeUtil() {
        defaultKaptcha = new DefaultKaptcha();
        properties = new Properties();
        // 图片边框
        properties.setProperty("kaptcha.border", "no");
        // 边框颜色
        properties.setProperty("kaptcha.border.color", "black");
        //边框厚度
        properties.setProperty("kaptcha.border.thickness", "1");
        // 图片宽
        properties.setProperty("kaptcha.image.width", "200");
        // 图片高
        properties.setProperty("kaptcha.image.height", "50");
        //图片实现类
        properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
        //文本实现类
        properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");
        //文本集合,验证码值从此集合中获取
        properties.setProperty("kaptcha.textproducer.char.string", "01234567890");
        //验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        //字体
        properties.setProperty("kaptcha.textproducer.font.names", "宋体");
        //字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        //文字间隔
        properties.setProperty("kaptcha.textproducer.char.space", "5");
        //干扰实现类
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
        //干扰颜色
        properties.setProperty("kaptcha.noise.color", "blue");
        //干扰图片样式
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
        //背景实现类
        properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");
        //背景颜色渐变,结束颜色
        properties.setProperty("kaptcha.background.clear.to", "white");
        //文字渲染器
        properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
    }

    public static VerifyCodeUtil code() {
        return new VerifyCodeUtil();
    }

    public String getCode(HttpServletResponse response) {
        return getCode(response, null);
    }

    public VerifyCodeUtil setSize(int width, int height) {
        // 图片宽
        properties.setProperty("kaptcha.image.width", ""+width);
        // 图片高
        properties.setProperty("kaptcha.image.height", ""+height);

        return this;
    }

    public VerifyCodeUtil setLength(int length) {
        //验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", ""+length);

        return this;
    }

    public VerifyCodeUtil setRandText(String text) {
        //文本集合,验证码值从此集合中获取
        properties.setProperty("kaptcha.textproducer.char.string", text);

        return this;
    }

    public String getCode(HttpServletResponse response, String code) {
        byte[] captchaChallengeAsJpeg;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

        // 生成验证码字符串并保存到session中
        String createText = defaultKaptcha.createText();
        if(code != null) {
            createText = code;
        }

        // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = defaultKaptcha.createImage(createText);
        try {
            ImageIO.write(challenge,"jpg",jpegOutputStream);
        } catch (IOException e) {
            return null;
        }
        // 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/jpeg");
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            servletOutputStream.write(captchaChallengeAsJpeg);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (IOException e) {
            return null;
        }
        return createText;
    }
}

3、在controller中使用

package com.shenmazong.controller;

import com.shenmazong.utils.VerifyCodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2022/2/12 11:43
 */

@Controller
public class VerifyCodeController {

    // 默认验证码
    @GetMapping(value = "/code1")
    public String code1(HttpServletResponse response) {
        String code = VerifyCodeUtil.code().getCode(response);
        // 把验证码放入redis
        System.out.println("code1="+code);
        return code;
    }

    // 调试模式
    @GetMapping(value = "/code2")
    public String code2(HttpServletResponse response) {
        String code = VerifyCodeUtil.code().getCode(response, "1234");
        // 把验证码放入redis
        System.out.println("code2="+code);
        return code;
    }

    // 调试模式
    @GetMapping(value = "/code3")
    public String code3(HttpServletResponse response) {
        String code = VerifyCodeUtil.code().setLength(6).getCode(response);
        // 把验证码放入redis
        System.out.println("code3="+code);
        return code;
    }

    // 设置随机字典
    @GetMapping(value = "/code4")
    public String code4(HttpServletResponse response) {
        String code = VerifyCodeUtil.code().setRandText("ABCD%").getCode(response);
        // 把验证码放入redis
        System.out.println("code4="+code);
        return code;
    }

    // 设置验证码图片的大小
    @GetMapping(value = "/code5")
    public String code5(HttpServletResponse response) {
        String code = VerifyCodeUtil.code().setSize(200, 80).getCode(response);
        // 把验证码放入redis
        System.out.println("code5="+code);
        return code;
    }
}

参考文章