JAVA生成圖片驗證碼



需用ajax到后台請求


@Controller
public class RandomPictureController extends ControllerUtil {

	/*
	 * 隨機字符字典
	 */
	private static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8',
			'9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
			'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

	/*
	 * 隨機數
	 */
	private static Random random = new Random();

	/*
	 * 獲取6位隨機數
	 */
	private static String getRandomString() {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < 4; i++) {
			buffer.append(CHARS[random.nextInt(CHARS.length)]);
		}
		return buffer.toString();
	}

	/*
	 * 獲取隨機數顏色
	 */
	private static Color getRandomColor() {
		return new Color(random.nextInt(255), random.nextInt(255), random
				.nextInt(255));
	}

	/*
	 * 返回某顏色的反色
	 */
	private static Color getReverseColor(Color c) {
		return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c
				.getBlue());
	}

	/**
	 * 生成驗證碼
	 * 
	 * @return String
	 */
	@RequestMapping("/rand_getCode.html")
	public void getCode(HttpServletRequest request, HttpServletResponse response) {
		try {
			int width = 63;
	        int height = 37;
	        Random random = new Random();
	        //設置response頭信息
	        //禁止緩存
	        response.setHeader("Pragma", "No-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expires", 0);

	        //生成緩沖區image類
	        BufferedImage image = new BufferedImage(width, height, 1);
	        //產生image類的Graphics用於繪制操作
	        Graphics g = image.getGraphics();
	        //Graphics類的樣式
	        g.setColor(this.getRandColor(200, 250));
	        g.setFont(new Font("Times New Roman",0,28));
	        g.fillRect(0, 0, width, height);
	        //繪制干擾線
	        for(int i=0;i<40;i++){
	            g.setColor(this.getRandColor(130, 200));
	            int x = random.nextInt(width);
	            int y = random.nextInt(height);
	            int x1 = random.nextInt(12);
	            int y1 = random.nextInt(12);
	            g.drawLine(x, y, x + x1, y + y1);
	        }

	        //繪制字符
	        String strCode = "";
	        for(int i=0;i<4;i++){
	            String rand = String.valueOf(random.nextInt(10));
	            strCode = strCode + rand;
	            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
	            g.drawString(rand, 13*i+6, 28);
	        }
	        //將字符保存到session中用於前端的驗證
	        request.getSession().setAttribute("strCode",strCode);
	        g.dispose();

	        ImageIO.write(image, "JPEG", response.getOutputStream());
	        response.getOutputStream().flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	Color getRandColor(int fc,int bc){
        Random random = new Random();
        if(fc>255)
            fc = 255;
        if(bc>255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r,g,b);
    }
}

/**
	 * 驗證碼驗證
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@RequestMapping("/rand_vaildata.html")
	public void vailDataCode(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		Map<String,String> mapStr=UtilJson.toMap(req.getParameter("mapStr"));
		String code = (String)req.getSession().getAttribute("strCode");//拿到緩存中的驗證碼
		Map<String, Object> mapInfo=new HashMap<String, Object>();
		if(code.equals(mapStr.get("code"))){
			mapInfo.put("code",SysFinal.SUCCESS);
			mapInfo.put("info", "");
		}else {
			mapInfo.put("code",SysFinal.FAIL);
			mapInfo.put("info", "驗證碼有誤");
		}
		this.respBack(UtilJson.mapToJson(mapInfo), resp);
	}



前台


/**
 * 刷新驗證碼
 * @param imgCode img對象ID
 */
function chageCode(){
    $('#imgCode').attr('src','rand_getCode.html?abc='+Math.random());//鏈接后添加Math.random,確保每次產生新的驗證碼,避免緩存問題。
}/**
*當失去焦點時就開始進行驗證
*
*/
$("#vaidataCodeInfo").blur(function(){
		var code=$("#vaidataCodeInfo").val();
		if(code==""){
			$("#verificationInfo").html("請填寫驗證碼");
		}
		var jsonObj={
				"code":code
		}
		var jsonAjax={
				"url":"rand_vaildata.html",
				"jsonData":{"mapStr":jsonToStr(jsonObj)},
				"methodName":"rand_vaildata"
		}
		getAjaxData(jsonAjax);
	});
});

/**
 * 驗證回調
 * @param jsonObj
 * @return
 */
function rand_vaildata(jsonObj){
	var data = strToJson(jsonObj.data);
	if (data.code=="fail") {
		$("#verificationInfo").html(data.info);
	}else{
		$("#verificationInfo").html(data.info);
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM