最代碼廣告位
allobject的gravatar頭像
allobject2013-01-09 20:46:18

java隨機生成圖片驗證碼

隨機生成兩種類型的驗證碼

public class CheckcodeServlet extends HttpServlet {
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//step1 創建一個圖片,創建一個內存映像對象
		BufferedImage image = new BufferedImage(60,20,BufferedImage.TYPE_INT_RGB);
		//得到畫筆
		Graphics g = image.getGraphics();
		Random r = new Random();
		//設置畫筆的顏色
		g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
		//設置整個畫板的背景顏色
		g.fillRect(0,0, 60, 20);
		//生成一個隨機數
		//String number = r.nextInt(99999) + "";
		String number = getNumber(5);
		//將number綁訂到session對象上。
		HttpSession session = request.getSession();
		session.setAttribute("number", number);
		g.setColor(new Color(0,0,0));
		g.drawString(number, 5, 15);
		//加一些干擾線
		for(int i=0;i<5;i++){
			g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
			g.drawLine(r.nextInt(60),r.nextInt(20),r.nextInt(60),r.nextInt(20));
		}
		//step2 壓縮圖片,然后輸出
		response.setContentType("image/jpeg");
		OutputStream output = response.getOutputStream();
		javax.imageio.ImageIO.write(image, "jpeg", output);
		
	}
	//隨機從"A~Z","0~9"當中取出5個字符
	private String getNumber(int length) {
		Random r = new Random();
		char[] chars = {'A','B','C','D','E','F','G',
				'H','I','J','K','L','M','N','O','P','Q',
				'R','S','T','U','V','W',	'X','Y','Z','0',
				'1','2','3','4','5','6','7','8','9'};
		String number = "";
		for(int i=0;i<length;i++){
			number += chars[r.nextInt(chars.length)];
		}
		return number;
	}


最代碼官方編輯于2014-1-23 22:13:06


AXIN編輯于2014-2-12 18:10:19


打賞

文件名:隨機生成驗證碼.rar,文件大小:2K下載
頂部客服微信二維碼底部
>掃描二維碼關注最代碼為好友掃描二維碼關注最代碼為好友
2008大乐透走势图