生成随机验证码图片JAVA代码

直接用java代码就可以生成随机验证码图片,具体流程如下:

1创建一张空白图片,同时指定宽高 理解为:搞一张白纸,准备画画

2通过图片获取绘制该图片的画笔,通过这个画笔就可以往该图片上绘制了

3随机生成个颜色涂满整张画布

4向画布上绘制文字

5随机生成若干条干扰线,也可以自己制定

   public static void main(String[] args) {
        //创建空白图片,用RGB来指定颜色
        BufferedImage image = new BufferedImage(
                70,30,BufferedImage.TYPE_INT_RGB
        );
        //获取画笔
        Graphics pencil = image.getGraphics();

        Random random = new Random();
        //随机生成个颜色涂满整张画布
        Color color = new Color(
                random.nextInt(256),
                random.nextInt(256),
                random.nextInt(256));
        pencil.setColor(color);//设置画笔颜色
        pencil.fillRect(0,0,70,30);

        //向画布上绘制文字,首先指定随机字符选取的范围
        String line = "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        pencil.setFont(new Font(null,Font.BOLD,20));
        for(int i=0;i<4;i++) {
            color = new Color(
                    random.nextInt(256),
                    random.nextInt(256),
                    random.nextInt(256));
            pencil.setColor(color);//设置画笔颜色
            String str = line.charAt(random.nextInt(line.length())) + "";
            pencil.drawString(str, i*15+5, 18+ random.nextInt(11)-5);
        }

        //随机生成3条干扰线
        for(int i=0;i<3;i++){
            color = new Color(
                    random.nextInt(256),
                    random.nextInt(256),
                    random.nextInt(256));
            pencil.setColor(color);//设置画笔颜色
            pencil.drawLine(random.nextInt(71), random.nextInt(31),
                       random.nextInt(71), random.nextInt(31));
        }
        //设置图片后缀,并通过输出流输出
        try {
            ImageIO.write(image,"jpg",
                          new FileOutputStream("./random.jpg"));
            System.out.println("图片已生成");
        } catch (IOException e) {
            e.printStackTrace();
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值