String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; //随机 Random random = new Random(); //验证码,图片 int fontCount = 4; //生成一张图片 int width = 60; int height = 30; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //须要得到画板 Graphics g = bi.getGraphics(); //画笔的颜色 g.setColor(Color.black); g.fillRect(0, 0, width, height); //画一张白图 g.setColor(Color.white); g.fillRect(1, 1, width-2, height-2); //设置字体大小 g.setFont(new Font("宋体",Font.BOLD,24)); //设置字 for(int i = 0 ; i < fontCount; i ++){ //设置颜色 g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); //得到随机的字 int index = random.nextInt(52); String str = data.substring(index, index+1); //将随机字 写入到画笔 g.drawString(str, (i+1)*(width / (fontCount + 2)),20); } //干扰线 for(int i = 0 ; i < 10;i++){ g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); } //设置头,告诉浏览器是一张图片 response.setContentType("image/jpeg"); //提示浏览器不能缓存 /* * <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> */ response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-cache"); response.setHeader("expires", "0"); //将生成的图片写入到浏览器 image/jpeg ImageIO.write(bi, "jpeg", response.getOutputStream());