1 //用画布做一个验证码 2 @WebServlet("/image.do") 3 public class ImageCodeServlet extends HttpServlet { 4 private static final long serialVersionUID = 1L; 5 6 //设置画布的长宽以及验证码的字的个数 7 static int width=100; 8 static int height=40; 9 static int size=4; 10 11 static Random random=new Random(); 12 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 13 14 //1 获取一个人画布 15 /** 16 * BufferedImage.TYPE_INT_RGB 画布的三原色 17 */ 18 BufferedImage bi=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB ); 19 20 //2 获取画笔 21 Graphics graphics=bi.getGraphics(); 22 23 //3 给画笔设置一个颜色 24 graphics.setColor(getColor()); 25 26 //4 作画 27 //4.1 画框 长宽;给画布填充一个背景色 28 //画一个长方形 坐标从0-0开始 29 graphics.fillRect(0, 0, width, height); 30 31 //4.2 往框里面写字 写之前设置好的size次 32 //设置会出现的字体 33 String str="qwertyuidhjcnx12345689AGDFCZMW"; 34 char[]ch=str.toCharArray(); 35 StringBuilder sb=new StringBuilder(); 36 37 for (int i = 0; i < size; i++) { 38 graphics.setColor(getFontColor()); 39 40 //写字的时候,Y坐标的位置:10-40 x坐标从5开始到95结束 41 42 int index=random.nextInt(ch.length); 43 44 graphics.drawString(ch[index]+"", i*15+random.nextInt(10), random.nextInt(25)+15); 45 46 sb.append(ch[index]); 47 } 48 49 //4.3 添加干扰 50 //添加点干扰 51 for (int i = 0; i < 300; i++) { 52 53 graphics.setColor(getColor()); 54 graphics.drawOval(random.nextInt(width), random.nextInt(height), 1, 1); 55 } 56 57 //添加线干扰 58 graphics.setColor(getColor()); 59 graphics.clearRect(random.nextInt(width), random.nextInt(height), random.nextInt(50), 1); 60 61 //把验证码的字符存储起来 62 request.getSession().setAttribute("code",sb.toString()); 63 64 //5 将画好的图片,使用流输出到前台 65 //将bi这个画笔以png的格式输出到前台 66 ImageIO.write(bi,"png",response.getOutputStream()); 67 68 } 69 70 //获取一个颜色对象,背景用浅色,文字用深色 71 private Color getColor(){ 72 73 int x; 74 int y; 75 int z; 76 77 do { 78 x=random.nextInt(250); 79 y=random.nextInt(250); 80 z=random.nextInt(250); 81 } while (!isDark(x, y, y)); 82 83 return new Color(x,y,z); 84 } 85 86 //字体用深色 87 private Color getFontColor(){ 88 89 int x; 90 int y; 91 int z; 92 93 do { 94 x=random.nextInt(250); 95 y=random.nextInt(250); 96 z=random.nextInt(250); 97 } while (isDark(x, y, y)); 98 99 return new Color(x,y,z); 100 } 101 102 103 /** 104 * 根据RGB值判断 深色与浅色 105 * @param r 106 * @param g 107 * @param b 108 * @return 109 */ 110 private boolean isDark(int r,int g,int b){ 111 if(r*0.299d + g*0.578d + b*0.114d >= 192){ //浅色 112 return false; 113 }else{ //深色 114 return true; 115 } 116 } 117 118 119 120 121 122 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 123 // TODO Auto-generated method stub 124 doGet(request, response); 125 }