JS图片压缩+图片上传前检测类型、大小、尺寸

原生JS压缩图片

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js压缩图片</title>
	</head>
	<body>
		<img id="img" src="">
		<input id="file" type="file" onchange="upload()">
	</body>
	<script>
		async function upload() {
			let fileObj = document.getElementById('file').files[0] //上传文件的对象
			try {
				// 开启上传文件前检测
				let imageSize = await beforeUpload(fileObj)
				if (imageSize) {
					let initSize = (fileObj.size / 1024).toFixed(2)
					let reader = new FileReader()
					reader.readAsDataURL(fileObj)
					reader.onload = function(e) {
						let image = new Image() //新建一个img标签
						image.src = e.target.result
						image.onload = function() {
							let setImg = compressImg(image, fileObj)
							document.getElementById('img').src = setImg
							//如果原图小于压缩后的就长传压缩图
							if (getImgSize(setImg) < (initSize * 1024)) {
								console.log('长传压缩后的图片')
							} else {
								console.log('长传原图')
							}
						}
					}
				}
			} catch (e) {
				console.log(e);
			}
		}
		// 对图片进行压缩
		function compressImg(img, fileObj, quality = 0.7, width = 1, height = 1) {
			let canvas = document.createElement('canvas'),
				context = canvas.getContext('2d'),
				imageWidth = img.width / width,
				imageHeight = img.height / height,
				result = '';
			canvas.width = imageWidth
			canvas.height = imageHeight
			context.drawImage(img, 0, 0, imageWidth, imageHeight)
			result = canvas.toDataURL('image/jpeg', quality)
			return result
		}

		function getImgSize(base64url) {
			//获取base64图片大小,
			var str = base64url.replace('data:image/jpeg;base64,', ''); //这里根据自己上传图片的格式进行相应修改
			var strLength = str.length;
			var fileLength = parseInt(strLength - (strLength / 8) * 2);
			// 由字节转换为Kb
			var size = "";
			size = (fileLength / 1024).toFixed(2)
			return parseInt(size);
		}

		//检测图片尺寸
		const getFileWidthAndHeight = (file, initwidth, initheight) => {
			return new Promise((resolve, reject) => {
				let width = initwidth;
				let height = initheight;
				let _URL = window.URL || window.webkitURL;
				let img = new Image();
				img.src = _URL.createObjectURL(file);
				img.onload = function() {
					if (img.width > width || img.height > height) {
						reject(`上传尺寸最大${initwidth}px * ${initheight}px!`);
					} else {
						resolve(true);
					}
				};
			});
		};
		// 上传文件前
		const beforeUpload = (file) => {
			const isJpgOrPng =
				file.type === "image/jpeg" ||
				file.type === "image/png" ||
				file.type === "image/bmp";
			//临时关闭校验
			if (!isJpgOrPng) {
				console.log('你必须上传 JPG/PNG 文件!');
				return false;
			}
			const isLt3M = file.size / 1024 / 1024 < 3;
			if (!isLt3M) {
				console.log('图像必须小于3MB!');
				return false;
			}
			//开启检测尺寸
			return getFileWidthAndHeight(file, 500, 500);
		};
	</script>
</html>


你可能感兴趣的:(笔记,javascript,前端,html5)