js canvas 图片压缩 并转换为 file 类型文件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="jquery-3.1.1.min.js"></script>
		<style type="text/css">
			
		</style>
	</head>
	<body>
		<input id="img-files4" type="file" accept="image/*" onchange="getInfo(event)" />
	
	</body>
	<script type="text/javascript">
		function getInfo(event){
			
			let reader = new FileReader();
			//这里把一个文件用base64编码
			reader.readAsDataURL(event.target.files[0]);			
			reader.onload = function(e){
				let newImg = new Image();
				//获取编码后的值,也可以用this.result获取
				newImg.src = e.target.result;
				newImg.onload = function () {
					/* 获取  this.height tthis.width*/
					var dataURL = compress(newImg,this.width,this.height,0.8);
					/*为了兼容ios 需要 dataURL-> blob -> file */
					var blob = dataURLtoBlob(dataURL);		// dataURL-> blob 
					var file = blobToFile(blob, '999');		// blob -> file
					console.log("得到文件:"+file);	
					console.log("压缩后大小:"+file.size/1024);				
					$("body").append("<img src='" + dataURL + "' />");
					
				}
			}
			
		}	
				
		function compress(img, width, height, ratio) { // img可以是dataURL或者图片url
			/*	如果宽度大于 750 图片太大 等比压缩 	*/
			if(width > 750){
				var ratio = width/height;
				width = 750;
				height = 750/ratio;
			}		
			var canvas, ctx, img64;
			canvas = document.createElement('canvas');
			canvas.width = width;
			canvas.height = height;
			

			ctx = canvas.getContext("2d");
			ctx.drawImage(img, 0, 0, width, height);
			/* canvas.toDataURL(mimeType(图片的类型), qualityArgument(图片质量)) */
			img64 = canvas.toDataURL("image/jpeg", ratio);

			return img64; // 压缩后的base64串
		}
		//将base64转换为blob
		function dataURLtoBlob (dataurl) { 
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new Blob([u8arr], { type: mime });
		}
		//将blob转换为file
		function blobToFile(theBlob, fileName){
		   theBlob.lastModifiedDate = new Date();
		   theBlob.name = fileName;
		   return theBlob;
		}
	</script>
</html>

猜你喜欢

转载自blog.csdn.net/guohao326/article/details/86382024