生成验证码的工具类

package com.htc.utils;

import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Component
public class CodeUtils {

    public  void code(HttpSession session, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        //设置页面不能缓存
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Pragma","No-cache");
        response.setDateHeader("Expires", 0);

        int width=60,height=30;

        //  绘制带缓冲区的图片
        BufferedImage pic = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        Graphics gc = pic.getGraphics();

        gc.setColor(getRandomColor(200,255));  //设置画布的背景 颜色
        gc.fillRect(0,0,width,height);//填充矩形
        gc.setFont(new Font("宋体",Font.PLAIN,20));

        //设置干扰线

        Random r = new Random();
        for (int i = 0; i <300 ; i++) {
            int x1= r.nextInt(width);
            int y1= r.nextInt(height);
            int x2= r.nextInt(15);
            int y2= r.nextInt(15);
            gc.setColor(getRandomColor(160,200));  //设置画布的背景 颜色
            gc.drawLine(x1,y1,x2,y2);
        }

        //设置干扰点
        for (int i = 0; i <150 ; i++) {
            int x1= r.nextInt(width);
            int y1= r.nextInt(height);

            gc.setColor(getRandomColor(100,160));  //设置画布的背景 颜色
            gc.drawOval(x1,y1,0,0);
        }

        //生成验证码
        String  RS= r.nextInt(9000)+1000+"";

        gc.setColor(getRandomColor(0,100));  //设置字体的背景 颜色

        gc.drawString(RS,10,16);

        gc.dispose();
        //你需要判断用户输入的验证码和你产生的验证码是否一致
        session.setAttribute("random",RS);

        ImageIO.write(pic,"JPEG",response.getOutputStream());
    }

    public  Color getRandomColor(int min,int max){
        //    0   -- 255
        Random radom = new Random();
        if(min>255){
            min=255;
        }
        if(max>255){
            max=255;
        }
        int  r = radom.nextInt(max-min)+min;
        int  g = radom.nextInt(max-min)+min;
        int  b = radom.nextInt(max-min)+min;

        return new Color(r,g,b);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值