java随机图片验证码

1. 验证码工具类

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class VerifyUtil {

    // 验证码字符集
    private static final char[] CHARS = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };
    // 字符数量
    private static final int SIZE = 6;
    // 干扰线数量
    private static final int LINES = 5;
    // 宽度
    private static final int WIDTH = 120;
    // 高度
    private static final int HEIGHT = 40;
    // 字体大小
    private static final int FONT_SIZE = 30;

    /**
     * 生成随机验证码及图片
     */
    public static Map<String, Object> createImage() {
        StringBuffer sb = new StringBuffer();
        // 1.创建空白图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 2.获取图片画笔
        Graphics graphic = image.getGraphics();
        // 3.设置画笔颜色
        graphic.setColor(Color.LIGHT_GRAY);
        // 4.绘制矩形背景
        graphic.fillRect(0, 0, WIDTH, HEIGHT);
        // 5.画随机字符
        Random ran = new Random();
        for (int i = 0; i < SIZE; i++) {
            // 取随机字符索引
            int n = ran.nextInt(CHARS.length);
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 设置字体大小
            graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));
            // 画字符
            graphic.drawString(CHARS[n] + "", i * WIDTH / SIZE, HEIGHT * 2 / 3);
            // 记录字符
            sb.append(CHARS[n]);
        }
        // 6.画干扰线
        for (int i = 0; i < LINES; i++) {
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 随机画线
            graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
        }
        // 7.返回验证码和图片
        Map<String, Object> map = new HashMap<>();
        //验证码
        map.put("code", sb.toString());
        //图片
        map.put("image", image);
        return map;
    }

    /**
     * 随机取色
     */
    public static Color getRandomColor() {
        Random ran = new Random();
        return new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));
    }
}

2. redis工具类

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class MyJedisUtils {
    
    public static final String HOST = "127.0.0.1";
    public static final Integer POST = 6379;
    public static JedisPool jedisPool;

    /**
     * 获取 redis 默认连接
     * @return
     */
    public static Jedis getJedis(){
        jedisPool = new JedisPool(HOST,POST);
        return jedisPool.getResource();
    }

    /**
     * 自定义获取 redis 连接
     * @param HOST
     * @param POST
     * @return
     */
    public static Jedis getJedis(String HOST,Integer POST){
        jedisPool = new JedisPool(HOST,POST);
        return jedisPool.getResource();
    }

    /**
     * 关闭 redis 连接
     * @param jedis
     */
    public static void closeJedis(Jedis jedis){
        if(jedis!=null&&jedis.isConnected()){
            jedis.close();
        }
    }
}


3. 控制层类

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


public class VerifyUtil {

    @GetMapping("code")
    @ResponseBody
    public Boolean code(String key_name, String code, HttpServletResponse response) throws IOException {
        // 获取到的值
        String key_value = null;
        // 获取redis连接
        Jedis jedis = MyJedisUtils.getJedis();
        if(code==null){
            Map<String, Object> map = VerifyUtil.createImage();
            //将图片输出给浏览器
            BufferedImage image = (BufferedImage) map.get("image");
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
            // redis 设置 5 分钟的存活时间
            jedis.setex(key_name,300,map.get("code").toString());
            return false;
        }
        key_value = jedis.get(key_name);
        // 关闭连接
        MyJedisUtils.closeJedis(jedis);
        Boolean result = code.equals(key_value);
        if(result){
            jedis.del(key_name);
        }
        return result;
    }
}

4. 页面代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="验证码:">
            <el-input v-model="formInline.code" placeholder="请输入验证码"></el-input>
        </el-form-item>
        <img id="code_image" src="" @click="code_image" alt="点击更换图片">
        <el-form-item>
            <el-button type="primary" @click="onSubmit">验证</el-button>
        </el-form-item>
    </el-form>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            formInline: {
                code: '',
                key_name: ""
            }
        },
        methods: {
            onSubmit() {
                if(this.formInline.code!=""){
                    axios.get("/code?code="+this.formInline.code+"&key_name="+this.formInline.key_name).then(data=>{
                        if(data.data){
                            this.$message({
                                message: '恭喜,验证成功!',
                                type: 'success'
                            });
                        }else{
                            this.$message.error('抱歉,验证错误!');
                        }
                    });
                }else{
                    this.$message.error('请输验证码!');
                }
            },
            code_image(){
                this.formInline.key_name = Math.random();
                document.getElementById("code_image").src="/code?key_name="+this.formInline.key_name;
            }
        },
        created(){
            this.code_image();
        }
    })
</script>
</body>
</html>

5. 效果

image

posted @ 2021-07-18 18:11  陈可儿  阅读(110)  评论(0编辑  收藏  举报