在html中添加
<canvas id="myCanvas" style="display: none">
??你的浏览器不支持canvas画布元素,请更新浏览器获得演示效果。
</canvas>
//1、设置压缩后的最大宽度 or 高度;
//2、设置压缩比例,根据图片的不同size大小,设置不同的压缩比。
???function compress(res,fileSize) { //res代表上传的图片,fileSize大小图片的大小
???????var img = new Image(),
???????????maxW = 640; //设置最大宽度
???????img.onload = function () {
???????????var cvs = document.getElementById(‘myCanvas‘),
???????????????ctx = cvs.getContext( ‘2d‘);
???????????if(img.width > maxW) {
???????????????img.height *= maxW / img.width;
???????????????img.width = maxW;
???????????}
???????????cvs.width = img.width;
???????????cvs.height = img.height;
???????????ctx.clearRect(0, 0, cvs.width, cvs.height);
???????????ctx.drawImage(img, 0, 0, img.width, img.height);
???????????var compressRate = getCompressRate(1,fileSize);
???????????var dataUrl = cvs.toDataURL( ‘image/jpeg‘, compressRate);
???????????document.body.appendChild(cvs);
???????????console.log(dataUrl);
// ???????????ctx.clearRect(0,0,cvs.width,cvs.height); 清空画布
// ???????????ctx.beginPath();
???????}
???????img.src = res;
https://my.oschina.net/zyxchuxin/blog/700381
H5相机上传图片压缩
原文地址:https://www.cnblogs.com/wangyuyanhello/p/8430920.html