图片压缩

258 阅读1分钟

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <title>上传文件压缩</title></head><body>  <div>    <h3>图片上传压缩</h3>    <input type="file"  id="file" placeholder="请上传图片" accept="image/*" />  </div></body></html><script>document.getElementById("file").addEventListener("change",function(e){  console.log("压缩前",e.target.files[0].size);  let result=e.target.files[0];  opload(result);
})function readImg(file){ return new Promise((resolve,reject)=>{   const img=new Image();   const reader=new FileReader();   reader.onload=function(e){     img.src=e.target.result;     console.log(e);   }   reader.onerror=function(e){      reject(e);   }   reader.readAsDataURL(file);   img.onload=function(){     resolve(img);   }   img.onerror=function(){     reject(e);   } })}//图片压缩function compressImg(img, type, mx, mh) {  return new Promise((resolve, reject) => {    const canvas = document.createElement('canvas');    const context = canvas.getContext('2d');    const { width: originWidth, height: originHeight } = img;    // 最大尺寸限制    const maxWidth = mx;    const maxHeight = mh;    // 目标尺寸    let targetWidth = originWidth;    let targetHeight = originHeight;    if (originWidth > maxWidth || originHeight > maxHeight) {      if (originWidth / originHeight > 1) {        //  宽图片        targetWidth = maxWidth;        targetHeight = Math.round(maxWidth * (originHeight / originWidth))      } else {        // 高图片        targetHeight = maxHeight;        targetWidth = Math.round(maxHeight * (originWidth / originHeight));      }    }    canvas.width = targetWidth;    canvas.height = targetHeight;    context.clearRect(0, 0, targetWidth, targetHeight);    // 图片绘制    context.drawImage(img, 0, 0, targetWidth, targetHeight);    canvas.toBlob(function(blob) {      console.log(blob);      resolve(blob);    }, type || 'image/png')  })}
 async function opload(file){  const img=await readImg(file);  console.log(img);  const blob=await compressImg(img,file.type,1000,1000);  const formData=new FormData();  console.log("压缩后",blob);  formData.append("file",blob,`file_${Date.parse(new Date())}.jpg`);}</script>