element-ui 图片压缩上传


export const compressImgNew = (file) => {
  return new Promise(resolve => {
    const reader = new FileReader()
    const image = new Image()
    image.onload = (imageEvent) => {
      const canvas = document.createElement('canvas') // 创建画布
      const context = canvas.getContext('2d')         // 画布为2d
      // const width = image.width / 1.05        // 图片宽度 / 压缩比例
      // const height = image.height / 1.05        // 图片高度 / 压缩比例
      const width = image.width / 3       // 图片宽度 / 压缩比例
      const height = image.height / 3       // 图片高度 / 压缩比例
      canvas.width = width                            // 画布宽度
      canvas.height = height                          // 画布宽度
      context.clearRect(0, 0, width, height)
      context.drawImage(image, 0, 0, width, height)
      const dataUrl = canvas.toDataURL(file.type)     //图片转路径
      const blobData = dataURLtoBlob(dataUrl, file.type) //图片转二进制
      resolve(blobData)
    }
    reader.onload = e => { image.src = e.target.result }
    reader.readAsDataURL(file)
  })
};

//图片转二进制
function dataURLtoBlob(dataURL, type) {
  var binary = atob(dataURL.split(',')[1])
  var array = []
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i))
  }
  return new Blob([new Uint8Array(array)], { type: type })
}

使用

import { compressImgNew } from “@/assets/js/picture.js”;

    beforeAvatarUpload(file) {
      let types = [
        "image/jpeg",
        "image/jpg",
        "image/png"
      ];
      const isImage = types.includes(file.type);
      const isLtSize = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.warning("上传图片只能是 JPG、JPEG、PNG 格式!");
        return false;
      }
      if (!isLtSize) {
        this.$message.warning("上传图片大小不能超过 5MB!");
        return false;
      }
      return compressImgNew(file);
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

黑白两客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值