js 压缩图片

					var f = data[0];  //图片地址
					var xhr = new XMLHttpRequest()
					xhr.open('GET', f, true)
					xhr.responseType = 'blob'
					xhr.onload = function() {
						console.log("到此了");
						console.log(this.response.size);
						if(this.response.size>250000){
						    let img = new Image();  
							img.src = f; // 要压缩的图片 
							let width=0;
							let height=0;
							img.onload=function(){  
								width = img.width;  
								height = img.height;  
							 
								let canvas = document.createElement('canvas');
								let ctx = canvas.getContext('2d');
								canvas.width = width;
								canvas.height = height;
								var base64;
								//  将图片画到canvas上面   使用Canvas压缩  
								 canvas.setAttribute("width", width);
                                                                  canvas.setAttribute("height",height);
							    ctx.drawImage(this, 0, 0, width, height);
								//var base64 = canvas.toDataURL(this.response.type, 0.2);
								var base64 = canvas.toDataURL('image/png',0.2);
								console.log(base64);//最终获得base64位
								console.log("到此了");
						   }; 
						}else{
//此方法自行写 pathToBase64 pathToBase64(f).then(res=>{ console.log(res);直接转base64 }) }   

  

参考地址:

https://www.cnblogs.com/zhao1949/p/9177281.html

https://www.jq22.com/web-skill43

https://www.jb51.net/article/187561.htm

https://www.jianshu.com/p/d21193898339

https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLImageElement/Image

https://www.cnblogs.com/markor/articles/745281.html   [图片类处理]

posted @ 2021-01-21 23:29  小小强学习网  阅读(52)  评论(0编辑  收藏  举报