验证码的案例代码

     //创建一张图片
        //单位:像素
        BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
        
        //透明的玻璃
        //向画板上画内容之前必须先设置画笔.
        Graphics2D gra = image.createGraphics();
        
        gra.setColor(Color.WHITE);
        //从哪个坐标开始填充, 后两个参数,矩形区域
        gra.fillRect(0, 0, 200, 100);
        
        List<Integer> randList = new ArrayList<Integer>();
        Random random =new Random();
        for (int i = 0 ;i<4;i++) {
            randList.add(random.nextInt(10));
        }
        //设置字体
        gra.setFont(new Font("宋体",Font.ITALIC|Font.BOLD,40));
        Color[] colors = new Color[]{Color.RED,Color.YELLOW,Color.BLUE,Color.GREEN,Color.PINK,Color.GRAY};
        for (int i = 0; i < randList.size(); i++) {
            gra.setColor(colors[random.nextInt(colors.length)]);
            gra.drawString(randList.get(i)+"", i*40, 70+(random.nextInt(21)-10));
        }
        
        for (int i = 0; i < 2; i++) {
            gra.setColor(colors[random.nextInt(colors.length)]);
            //画横线
            gra.drawLine(0, random.nextInt(101), 200, random.nextInt(101));
        }
        
        ServletOutputStream outputStream = resp.getOutputStream();
        //工具类
        ImageIO.write(image, "jpg", outputStream);
        
        //把验证码放入到session中
        HttpSession session = req.getSession();
        session.setAttribute("code", ""+randList.get(0)+randList.get(1)+randList.get(2)+randList.get(3));

 

转载于:https://www.cnblogs.com/chyxOne/p/9971901.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值