Java生成驗證碼

代碼如下:
                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();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章