springboot生成图片验证码方法

public class VerifyCode {
    
    /*在下面字符内生成校验码*/
    private String VERIFY_CODES = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";

    public String generateVerifyCode(HttpServletResponse response) throws IOException {
        int IMG_WIDTH = 72;
        int IMG_HEIGHT = 30;
        Random random = new Random();
        BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,IMG_WIDTH,IMG_HEIGHT);
        g.setFont(new Font("楷体",Font.BOLD,25));
        /* #1 提供变量保存随机字符数据 */
        StringBuilder sb = new StringBuilder();
        for(int i = 1 ; i <= 4 ; i ++){
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            int len = random.nextInt(VERIFY_CODES.length());
            String str = VERIFY_CODES.substring(len,len+1);
            /* #2 存放随机字符串 */
            sb.append( str );
            g.drawString(str, IMG_WIDTH / 6 * i , 22 );
        }

        /* #3 获得随机字符串 */
        String randomStr = sb.toString();

        // 生成随机干扰线
        for (int i = 0; i < 30; i++) {
            //随机颜色
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            int x = random.nextInt(IMG_WIDTH - 1);
            int y = random.nextInt(IMG_HEIGHT - 1);
            int x1 = random.nextInt(12) + 1;
            int y1 = random.nextInt(6) + 1;
            g.drawLine(x, y, x - x1, y - y1);
        }
         /*通过response接口返回图片内容*/
        ImageIO.write(image,"jpeg", response.getOutputStream());
        return randomStr;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

二九筒

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

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

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

打赏作者

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

抵扣说明:

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

余额充值