JAVA验证码生成器

JAVA验证码生成器


/*

 * 验证码:

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

 */

public class CheckImage {

    public static void main(String[] args) throws IOException {

 

        int width = 120;

        int height = 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 (int i = 1; i <= 12; i++) {

            // 设置画笔的颜色

            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

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

                    r.nextInt(height));

        }

 

        int x = 10;

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

            // 设置画笔的颜色

            g.setColor(new Color(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"));

 

    }

}