java代码,实现验证码制作

//验证码测试
        //1创建一张空图片,并且指定宽高。 理解为:创建一张画纸
        BufferedImage image =  new BufferedImage(70,30,BufferedImage.TYPE_INT_RGB);

        //2根据图片获取一个画笔,通过该画笔画的内容都会画到该图片上
        Graphics g = image.getGraphics();

        //3确定验证码内容(字母与数字的组合)
        String line = "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();//用于生成随机数(随机数位line的字符下标)

        //为图片背景填充一个随机颜色
        //创建Color时,需要指定三个参数,分别是,红,绿,蓝。数字范围都是(0-255)之间
        Color bgcolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
        //将画笔设置为该颜色
        g.setColor(bgcolor);
        //填充整张图片为画笔当前颜色
        g.fillRect(0,0,70,30);

        //向图片上画4个字符
        for(int i=0;i<4;i++) {
            //随机生成一个字符
            String str = line.charAt(random.nextInt(line.length())) + "";
            //生成随机颜色
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            //设置画笔颜色
            g.setColor(color);
            //设置字体
            g.setFont(new Font(null, Font.BOLD, 20));
            //将字符串画到图片指定的位置上
            g.drawString(str, i*15+5, 18+ random.nextInt(11)-5);
        }

        //随机生成4条干扰线
        for (int i=0;i<4;i++){
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            g.setColor(color);
            g.drawLine(random.nextInt(71), random.nextInt(31),
                       random.nextInt(71), random.nextInt(31));
        }

        //将图片写入文件来生成该图片文件
        try {
            ImageIO.write(image,"jpg",new FileOutputStream("./random.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值