Home > Web Front-end > JS Tutorial > js method to verify image size

js method to verify image size

一个新手
Release: 2017-10-14 09:36:26
Original
2304 people have browsed it

/**
	 * 要校验尺寸的图片元素的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);
		};
	}
Copy after login

The above is the detailed content of js method to verify image size. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template