js校驗圖片尺寸

/**
	 * 要校驗尺寸的圖片元素的id,寬,高
	 */
	function checkResolution(id, width, height) {
		// 獲取該圖片元素
		var obj = document.getElementById(id);
		var url, image;
		// 獲取元素的url源
		if (obj.files && obj.files[0]) {
			if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
				obj.select();
				url = document.selection.createRange().text;
			}
			url = window.URL.createObjectURL(obj.files[0]);
		} else {
			url = obj.value;
			url = "file:///" + url;
		}
		// 構建圖片
		image = new Image();
		image.src = url;
		// 加載圖片
		return image.onload = function() {
			// 如果直接校驗的話image.width與image.height還未賦值,所以設置延遲1ms後校驗
			setTimeout(function() {
				if (image.width != width || image.height != height) {
					// 校驗不通過,返回false
					alert(id + "上傳的尺寸爲:" + image.width + "*" + image.height
							+ ",應上傳:" + width + "*" + height);
					return false;
				}
				// 校驗通過,返回true
				return true;
			}, 1);
		};
	}


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