使用canvas压缩图片大小(转载处:https://www.xuanmo.xin/details/3189)
(效果图)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>canvas压缩图片大小</title> </head> <body> <div class="yimage"> <form id="form"> <input type="file" name="file" multiple="multiple"> </form> </div> <div class="image"> <img src="" width="50%" height="30%"> </div> <div class="ysimage"> <img src=""> </div> <script src="jquery-1.10.2.min.js"></script> <script type="module"> /** * [imageCompress 图片压缩] * @param {[Array]} imgSrc [传入图片地址] * @param {Number} [width=1024] [图片需要压缩的宽度,单位:px] * @param {Number} [quality=1] [图片需要压缩的质量,0~1之间] * @return {[type]} [返回base64 jpeg格式图片] */ export function imageCompress (imgSrc, width = 1024, quality = 1) { let imgList = [] imgSrc.map(v => { let img = new Promise((resolve, reject) => { let canvas = document.createElement('canvas') let ctx = canvas.getContext('2d') let oImg = new window.Image() oImg.src = v oImg.onload = function () { let height = width / (this.naturalWidth / this.naturalHeight) // 如果压缩的宽度大于图片自身的宽度,采取图片自身的宽度 if (this.naturalWidth <= width) { width = this.naturalWidth height = this.naturalHeight } canvas.width = width canvas.height = height ctx.drawImage(this, 0, 0, width, height) resolve(canvas.toDataURL('image/jpeg', quality)) } }) imgList.push(img) }) return Promise.all(imgList).then(res => Promise.resolve(res)) } $(document).ready(function(){ // imageCompress("/timg.jpg"); $("input[name='file']").on("change",function(){ var reader = new FileReader(); reader.onload = function(e) { var data=[]; data.push(e.target.result); $(".image").find("img").attr("src",e.target.result); var imgebase4=imageCompress(data,300,0.3); imgebase4.then( function (val) { $(".ysimage").find("img").attr("src",val[0]); }, function (reason) { // console.log('Handle rejected promise (' + reason + ') here.'); }); } reader.readAsDataURL(document.querySelector("input[type=file]").files[0]); }); }) </script> </body> </html>