[VUE小课堂]前端利用JS处理图片压缩

由于之前没人维护项目,图片数据库马上就要炸了,今天搞了个上传图片压缩的小功能来缓解以后的压力

使用了EL-UPLOAD来做示例,以及compressorjs处理压缩。

首先安装compressorjs

npm install compressorjs --save

JS部分

在方法中使用了compressImage 方法压缩图片,由于测试没有服务器就将图片保存到本地。同时,我们添加了两个新的方法blobUrlToBlob和downloadFile。blobUrlToBlob方法是将base64编码后的图片链接转化为Blob对象。 downloadFile方法则是兼容不同浏览器,将图片下载到本地。

如果文件的 MIME 类型与 new Blob() 构造函数传递的类型不匹配,则可能导致解码错误。

示例代码中已经修改成file格式。

<script>
import Compressor from 'compressorjs';

export default {
  data () {
    return {
      fileList: []
    };
  },
  methods: {
    compressImage (file) {
      return new Promise((resolve, reject) => {
        new Compressor(file, {
          quality: 0.8, // 压缩质量
          maxWidth: 800, // 压缩后的最大宽度
          maxHeight: 1200, // 压缩后的最大高度
          success (result) {
            resolve(result);
          },
          error (err) {
            reject(err);
          },
        });
      });
    },
    downloadFile (file, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(file, filename);
      } else {
        const link = document.createElement('a');
        const body = document.querySelector('body');

        link.href = window.URL.createObjectURL(file);
        link.download = filename;

        // fix Firefox
        link.style.display = 'none';
        body.appendChild(link);

        link.click();
        body.removeChild(link);

        window.URL.revokeObjectURL(link.href);
      }
    },
    beforeUpload (file) {
      this.fileList.push(file);
      return false;
    },
    handleSuccess (response, file, fileList) {
      console.log("上传成功");
    },
    handleError (err, file, fileList) {
      console.log("上传失败");
    },
    async handleChange (file, fileList) {
      const compressedFile = await this.compressImage(file.raw);
      const fileObj = new File([compressedFile], file.name, { type: compressedFile.type });
      this.downloadFile(fileObj, file.name);
    },
    blobToFile (blob, fileName) {
      return new File([blob], fileName, { type: blob.type });
    },
    blobUrlToBlob (dataURI) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open('GET', dataURI, true);
        xhr.responseType = 'blob';
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          } else {
            reject(new Error('下载文件失败'));
          }
        };

        xhr.send();
      });
    }
  }
};
</script>

至此整个下载流程完成

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时光已回不到旧日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值