0
点赞
收藏
分享

微信扫一扫

Java后台生成登录验证码

夏沐沐 09-05 11:00 阅读 1

一、验证码效果

在这里插入图片描述

二、实现代码

VerifyCodeController.java

package com.xxl.sso.server.controller;

import com.xxl.sso.server.Util.JedisUtil;
import com.xxl.sso.server.Util.VerifyCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by Wangdeyu on 2024/3/27.
 */
@Controller
@RequestMapping("/sso")
public class VerifyCodeController {

    /* 获取验证码图片*/
    @RequestMapping("/getVerifyCode")
    public void getVerificationCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            int width = 180;
            int height = 60;

            // 生成初始画布
            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 生成图片和验证码
            String randomText = VerifyCode.drawRandomText(width, height, verifyImg);

            // 得到session
            String sessionId = request.getSession().getId();

            // 存入redis
            JedisUtil.setObjectValue(sessionId, randomText, 1 * 60);  // second

            // 返回验证图片
            System.out.println("获取验证码:" + randomText);
            response.setContentType("image/png");//必须设置响应内容类型为图片,否则前台不识别
            OutputStream os = response.getOutputStream(); //获取文件输出流
            ImageIO.write(verifyImg, "png", os);//输出图片流

            os.flush();
            os.close();//关闭流

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

VerifyCode.java

package com.xxl.sso.server.Util;

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

/**
 * Created by Wangdeyu on 2024/3/27.
 */
public class VerifyCode {
    public static String drawRandomText(int width, int height, BufferedImage verifyImg) {

        Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();

        graphics.setColor(new Color(30, 109, 201));//设置画笔颜色-验证码背景色

        graphics.fillRect(0, 0, width, height);//填充背景

        graphics.setFont(new Font("微软雅黑", Font.BOLD, 40));

        //数字和字母的组合

        //String baseNumLetter ="123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
        String baseNumLetter ="123456789";
        StringBuffer sBuffer = new StringBuffer();
        int x = 20;  //旋转原点的 x 坐标
        String ch = "";
        Random random = new Random();

        // 随机生成4个字符和样式
        for (int i = 0; i < 4; i++) {
            graphics.setColor(getRandomColor());

            //设置字体旋转角度
            int degree = random.nextInt() % 25;  //角度小于30度
            int dot = random.nextInt(baseNumLetter.length());
            ch = baseNumLetter.charAt(dot) + "";
            sBuffer.append(ch);

            //正向旋转
            graphics.rotate(degree * Math.PI / 180, x, 45);
            graphics.drawString(ch, x, 45);
            //反向旋转
            graphics.rotate(-degree * Math.PI / 180, x, 45);
            x += 40;
        }

        //画干扰线
        for (int i = 0; i < 6; i++) {
            // 设置随机颜色
            graphics.setColor(getRandomColor());

            // 随机画线
            graphics.drawLine(random.nextInt(width), random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        }

        //添加噪点
        for (int i = 0; i < 30; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            graphics.setColor(getRandomColor());
            graphics.fillRect(x1, y1, 2, 2);
        }

        return sBuffer.toString();
    }

    /**
     * 随机取色
     */
    private static Color getRandomColor() {
        // 自定义颜色数组
        Color[] arr={new Color(255,255,255),new Color(184,250,255),new Color(107,184,255),new Color(57,208,255),new Color(124,169,255)};

        Random ran = new Random();
        int index = ran.nextInt(arr.length);

        return arr[index];
    }
}

举报
0 条评论