js /vue 实现图片压缩

不说废话,直接上代码

function yaFile(fileList) {
  return new Promise(function (resolve, reject) {
    console.log("fileList", fileList);
    let files = fileList[0].file;
    console.log("压缩前大小", files.size);
    const name = files.name; //文件名
    const reader = new FileReader();
    reader.readAsDataURL(files);
    reader.onload = function (e) {
      const src = e.target.result;
      const img = new Image();
      img.src = src;
      img.onload = function (e) {
        const w = img.width;
        const h = img.height;
        const maxWidth = 1440;
        const width = maxWidth;
        const height = h / w * maxWidth;
        const quality = 0.8; // 默认图片质量为0.92
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const anw = document.createAttribute("width");
        anw.nodeValue = width;
        const anh = document.createAttribute("height");
        anh.nodeValue = height;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(img, 0, 0, width, height);
        ctx.fillRect(0, 0, width, height);
        const base64 = canvas.toDataURL('image/jpeg', quality); // 图片格式jpeg或webp可以选0-1质量区间
        // 返回base64转blob的值
        console.log(`原图${(src.length/1024).toFixed(2)}kb`, `新图${(base64.length/1024).toFixed(2)}kb`);
        let file = dataURLtoFile(base64, Date.parse(Date()) + '.jpg');
        var newfile = {
          content: base64,
          file: file
        };
        console.log("/压缩后的file", newfile); //压缩后的file
        console.log("压缩后的file大小", newfile.file.size); //压缩后的file
        console.log("newfile", newfile);
        resolve(newfile);
      }
      img.onerror = e => {
        error(e);
      }
    }
  });

}

2.加了Promise同步返回。

 

3.封装成工具类 imgUtils.js ,暴露出来

function yaFile(fileList) {
...
}
export default { yaFile }

  3.1 main.js引入

import imgUtil from '@/utils/imgUtil'

Vue.prototype.$imgUtil=imgUtil

 3.2 使用

afterRead() {
      this.$imgUtil.yaFile(this.fileList).then(res=>{
      this.ontpysFile=res;
      });
    }

 

posted @ 2021-11-18 17:00  拖肥  阅读(1432)  评论(0编辑  收藏  举报