1. 程式人生 > >HTML 點選圖片更換驗證碼的實現

HTML 點選圖片更換驗證碼的實現

有一些的網站的需要圖片驗證碼當你點選的時候可以變換驗證碼


<img style="height: 22px;" id="codeImg" onclick="this.src='verifycode?'+Math.random()"alt="點選更換" title="點選更換" src="verifycode" />
<!-- onclick="this.src='verifycode?'+Math.random()" 中的 verifycode 可以換成你自己請求的地址 -->


我的伺服器端程式碼

/**
 * 生成驗證碼
 * @param request  Http請求
 * @param response Http響應
 * @param session  Http會話
 */
@RequestMapping(value="/verifycode")
public void verifyCode(HttpServletRequest request, HttpServletResponse response,HttpSession session){
	try {
		int width = 60;
		int height = 30;
		Random random = new Random();
		//設定response頭資訊
		//禁止瀏覽器快取
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires",0);			
		BufferedImage image = new BufferedImage(width, height,1);//生成緩衝區image類
		
		Graphics graphics = image.getGraphics();//產生image類的Graphics用於繪製操作
		//Graphics類的樣式
		graphics.setColor(this.getRandColor(10,255));
		graphics.setFont(new Font("Times New Roman",0,28));
		graphics.fillRect(0, 0, width, height);			
		for(int i=0;i<40;i++){//繪製干擾線
			graphics.setColor(this.getRandColor(100,200));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(12);
			int y1 = random.nextInt(12);
			graphics.drawLine(x, y, x + x1, y + y1);
		}
		//繪製字元
		String verifycode = "";
		for(int i=0;i<4;i++){
			String rand = String.valueOf(random.nextInt(10));
			verifycode = verifycode + rand;
			graphics.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
			graphics.drawString(rand,12*i+6, 26);
		}
		System.out.println("當前: "+verifycode);
		session.setAttribute("VerifyCode", verifycode);//將字元儲存到session中用於前端的驗證
		graphics.dispose();
		ImageIO.write(image,"JPEG", response.getOutputStream());
		response.getOutputStream().flush();			
	} catch (Exception e) {
		throw new RuntimeException();
	} 

}

/**
 * 隨機顏色
 * @param bcolor 開始顏色值
 * @param ecolor 結束顏色值
 * @return
 */
private Color getRandColor(int bcolor,int ecolor){
	Random random = new Random();
	int r = bcolor + random.nextInt(ecolor - bcolor);
	int g = bcolor + random.nextInt(ecolor - bcolor);
	int b = bcolor + random.nextInt(ecolor - bcolor);
	return new Color(r,g,b);
}