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>


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值