<input id="file" type="file" accept=".png,.jpg,.jpeg,.gif">
// 使用compressImage(input.files[0], (file) => { // 这里可以就对压缩后的文件 file 一顿操作了(上传还是咋地,你高兴就好) // handleUpload(file);}, (msg) => { console.error(msg);});/* 参数说明: file: 要压缩的图片文件 success: 成功回调 error: 错误回调*/function compressImage(file, success, error) { // 压缩图片需要的一些元素和对象 var reader = new FileReader(), img = new Image(); // 缩放图片需要的canvas var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); // base64 地址图片加载完毕后 img.onload = function () { // 图片原始尺寸 var originWidth = this.width; var originHeight = this.height; // 最大尺寸限制 var maxWidth = 1080, maxHeight = 1080; // 目标尺寸 var targetWidth = originWidth, targetHeight = originHeight; // 图片尺寸超过1080x1080的限制 if (originWidth > maxWidth || originHeight > maxHeight) { if (originWidth / originHeight > maxWidth / maxHeight) { // 更宽,按照宽度限定尺寸 targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (originHeight / originWidth)); } else { targetHeight = maxHeight; targetWidth = Math.round(maxHeight * (originWidth / originHeight)); } } // canvas对图片进行缩放 canvas.width = targetWidth; canvas.height = targetHeight; // 清除画布 context.clearRect(0, 0, targetWidth, targetHeight); // 图片压缩 context.drawImage(img, 0, 0, targetWidth, targetHeight); // canvas转为blob并执行success回调 canvas.toBlob(function (blob) { var result = new File([blob], file.name, { type: "image/png", }); success(result); }, file.type || 'image/png'); }; // 文件base64化,以便获知图片原始尺寸 reader.onload = function (e) { img.src = e.target.result; }; reader.onerror = (e) => { error(e); } // 选择的文件是图片 if (file.type.indexOf("image") == 0) { reader.readAsDataURL(file); } else { error("请选择图片文件"); }}
HTML5 file API加canvas实现图片前端JS压缩并上传