Java生成验证码

来源:互联网 发布:linux两台机器怎么连 编辑:程序博客网 时间:2024/04/25 09:37
代码如下:
                response.setContentType("image/jpeg");ServletOutputStream out = response.getOutputStream();// 定义验证码边框的长和高int width = 60;int height = 20;// 定义图片缓冲区,使用RGB模式输出图片BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);// 定义画笔工具对象Graphics graph = img.getGraphics();// 设置验证码框的背景颜色graph.setColor(new Color(200, 200, 200));// 使用上面设置的颜色填充整个矩形框graph.fillRect(0, 0, width, height);// 定义要显示的验证码StringBuffer codeStr = new StringBuffer("");// 定义验证码数组String code[] = { "A", "a", "B", "b", "C", "c", "D", "d", "E", "e","F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "K", "k","L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "Q", "q","R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "W", "w","X", "x", "Y", "y", "Z", "z", "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7","8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9","0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1","2", "3", "4", "5", "6", "7", "8", "9", "0", "1" };// 定义随机数对象Random rnd = new Random();// 使用for循环生成随机数,使用随机数从数组中取出字符作为验证码for (int i = 0; i < 4; i++) {//每循环一次取出一个字符String cStr = code[rnd.nextInt(104)];//设置每一个输出的验证码的颜色graph.setColor(new Color(rnd.nextInt(125),rnd.nextInt(125),rnd.nextInt(125)));//设置输出验证码的字体graph.setFont(new Font("",Font.PLAIN,20+rnd.nextInt(5)));//绘制每一个验证码graph.drawString(cStr, 15*i+rnd.nextInt(5), 20-rnd.nextInt(5));//将每一个验证码添加到整体验证码中codeStr.append(cStr);}//定义验证码字符串String codeInfo = codeStr.toString();//将验证码放在session中request.getSession().setAttribute("code", codeInfo);//随机产生100个干扰点   for (int i = 0; i < 100; i++)   {    int x = rnd.nextInt(width);    int y = rnd.nextInt(height);    graph.setColor(new Color(rnd.nextInt(185)+40,rnd.nextInt(185)+40,rnd.nextInt(185)+40));    //设置干扰点的位置长宽    graph.drawOval(x, y, 1, 1);   }   //将图片输出到页面上   ImageIO.write(img, "JPEG", out);out.flush();out.close();