前端压缩图片并转成base64上传

前端压缩图片并转成base64上传

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>图片压缩转base64</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
</head>
<body>
	<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

	<input id="file" type="file" accept="image/*"><br>
	<input type="button" id="btn" value="上传"><br />

	<script>
		var imgBase64 = ''
		$("#file").change(function () {
			var file = this.files[0];
            if(!/image\/\w+/.test(file.type)){
                alert("请确保文件为图像类型"); 
                return false; 
            }
			
			//小于2m直接转base64,大于2m的还需要压缩处理
			if(file.size < 2 * 1024 * 1024){
				var reader=new FileReader();
            	reader.readAsDataURL(file);
            	reader.onload=function(){
                	imgBase64 = this.result.replace("image/jpeg", "image/png")
            	}
			} else {
				cutImageBase64(file, 900, 1);
			}
		})


		/**
		 * 超过2M先压缩再生成base64
		 * fiel 文件
		 * wid 图片压缩后的宽度(高度根据设置的宽度等比缩放)
		 * quality 清晰度0-1
		 */
		function cutImageBase64(file, wid, quality) {
			var canvas;
			var URL = window.URL || window.webkitURL;
			var blob = URL.createObjectURL(file);
			var img = new Image();
			img.src = blob;
			img.onload = function () {
				var that = this;
				//生成比例
				var w = that.width, h = that.height, scale = w / h;
				w = wid || w;
				h = w / scale;
				//生成canvas
				canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				$(canvas).attr({ width: w, height: h });
				ctx.drawImage(that, 0, 0, w, h);
				// 生成base64
				imgBase64 = canvas.toDataURL('image/png', quality || 0.9);
			};
		}

		//上传图片
		$('#btn').click(() => {
			$.ajax({
				type: "POST",
				url: "03.php", 
				data: { img: imgBase64 },
				success: function (res) {
					console.log(res);
				}
			});
		})
	</script>
</body>

你可能感兴趣的:(前端,前端)