JAVA验证码生成器

来源:互联网 发布:网络专题策划方案 编辑:程序博客网 时间:2024/05/21 16:23


/*

 *验证码:

 *验证码是一张图片,而这个图片中的内容是使用代码生成的。

 */

publicclass CheckImage {

   publicstaticvoid main(String[]args)throws IOException {

 

       intwidth = 120;

       intheight = 40;

       //创建一个可以存储图片的缓冲区

       BufferedImagebufi = new BufferedImage(width,height,

              BufferedImage.TYPE_INT_RGB);

       /*

        *通过画布获取到针对这个画布的画笔

        */

       Graphicsg = bufi.getGraphics();

 

       //修改画布

       g.setColor(Color.WHITE);

       //填充画布

       g.fillRect(0, 0, width,height);

 

       //设置画布的边框

       g.setColor(Color.RED);

       g.drawRect(0, 0, width - 1,height - 1);

 

       //准备给图片上写的数据

       Stringdata = "qwertyupasdfghjkzxcvbnmQWERTYUPASDFGHJKLZXCVBNM0123456789";

 

       //创建一个获取随机数的对象

       Randomr = new Random();

 

       //给画布上画干扰线

       for (inti = 1;i <= 12;i++) {

          //设置画笔的颜色

          g.setColor(newColor(r.nextInt(255),r.nextInt(255),r.nextInt(255)));

          g.drawLine(r.nextInt(width),r.nextInt(height),r.nextInt(width),

                 r.nextInt(height));

       }

 

       intx = 10;

       for (inti = 1;i <= 4;i++) {

          //设置画笔的颜色

          g.setColor(newColor(r.nextInt(255),r.nextInt(255),r.nextInt(255)));

          //设置字体

          g.setFont(new Font("宋体", Font.ITALIC, 26));

          //给画布上写内容

          g.drawString(data.charAt(r.nextInt(data.length())) + "",x, 30);

          x += 24;

       }

 

       //需要把画布中的内容输出到指定位置

       ImageIO.write(bufi,"JPG",newFileOutputStream("e:/1.jpg"));

 

   }

}