Java/Spring/SpringBoot下原生代码无依赖生成验证码

2021-07-06 49点热度 0人点赞 0条评论

分享自用的Java下Spring/SpringBoot用于生成验证码的工具类,不依赖第三方库,利用Graphics绘图,另外加了背景干扰线等。

写在Controller中,请自行取用!

如果部署到Linux上无法生成验证码的问题,请查看:https://blog.terrynow.com/2021/07/03/centos-tomcat-cannot-generate-captcha-graphics-font-related-error-solved/

@RequestMapping(value = "/captcha.jpg", method = RequestMethod.GET, headers = "Accept=image/*", produces = "image/jpg")
@ResponseBody
public BufferedImage captcha(HttpSession session) {
    // 在内存中创建图象
    int width = 60;//宽度
    int height = 20;//高度
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    // 获取图形上下文
    Graphics g = image.getGraphics();

    // 生成随机类
    Random random = new Random();

    // 设定背景色
    g.setColor(getRandColor(200, 250));
    g.fillRect(0, 0, width, height);

    // 设定字体
    g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

    int disturbCount = 155;
    // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
    g.setColor(getRandColor(160, 200));
    for (int i = 0; i < disturbCount; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        g.drawLine(x, y, x + xl, y + yl);
    }

    int captchaLength = 4;
    // 取随机产生的认证码(4位数字)
    StringBuilder sRand = new StringBuilder();
    for (int i = 0; i < captchaLength; i++) {
        String rand = String.valueOf(random.nextInt(10));
        sRand.append(rand);
        // 将验证码码显示到图象中
        g.setColor(new Color(20 + random.nextInt(110),
                20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(rand, 13 * i + 6, 16);
    }

    // 将验证码存入SESSION,后续从session取出和用户输入的对比
    session.setAttribute("captcha", sRand.toString());
    // 图象生效
    g.dispose();

    return image;
}

/**
 * 给定范围生成随机颜色
 */
private Color getRandColor(int fc, int bc) {// 
    Random random = new Random();
    if (fc > 255)
        fc = 255;
    if (bc > 255)
        bc = 255;
    int r = fc + random.nextInt(bc - fc);
    int g = fc + random.nextInt(bc - fc);
    int b = fc + random.nextInt(bc - fc);
    return new Color(r, g, b);
}

正常的验证码如图所示:

 

admin

这个人很懒,什么都没留下

文章评论

*

code