JAVA验证码的简单实现

 		//设置宽高
        int width = 100;
        int height = 50;
        //创建图片对象
        BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //创建画笔对象
        Graphics grap = img.getGraphics();
        //设置颜色
        grap.setColor(Color.white);
        //填充背景色
        grap.fillRect(0,0,width,height);

        grap.setColor(Color.red);
        //创建边框
        grap.drawRect(0,0,width-1,height-1);

        grap.setColor(Color.black);
        //创建字符集
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        //写字符,随机生成字符
        for (int i = 1; i <= 4; i++) {
            int index = random.nextInt(str.length());
            char ch = str.charAt(index);
            grap.drawString(ch+"",width/5*i,height/2);
        }

        grap.setColor(Color.pink);
        //绘制干扰线,两点确定一线
        for (int i = 0; i < 8; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            grap.drawLine(x1,x2,y1,y2);
        }
        //输出验证码图片
        ImageIO.write(img,"jpg",resp.getOutputStream());

里面的各种颜色可以随意改变,按自己的喜好来进行,这是写在servlet中的代码块
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值