前端压缩图片

export function zipImg(file, limit = 200) {
  return new Promise(resolve => {
    if (file && file.size / 1024 > limit && file.type !== "image/gif") {
      let img = new Image()
      img.src = URL.createObjectURL(file)
      let cvs = document.createElement("canvas")
      let maxRatio = 0.7 // 大图比率
      let minRatio = 0.8 // 小图比率
      let imgQulity = 0.4 // 图像质量
      img.onload = async function () {
        let ratio =
          img.naturalWidth > 1000 || img.naturalHeight > 1000
            ? maxRatio
            : minRatio
        cvs.width = img.naturalWidth * ratio
        cvs.height = img.naturalHeight * ratio
        let ctx = cvs.getContext("2d")
        ctx.drawImage(img, 0, 0, cvs.width, cvs.height)
        // 压缩后新图的 base64
        let zipBase64 = cvs.toDataURL("image/jpeg", imgQulity)
        let fileFixed = await dataURLtoFile(zipBase64, file.name, "image/jpeg")
        console.log(fileFixed)
        if (fileFixed.size > file.size) {
          resolve(file)
        } else {
          if (fileFixed.size / 1024 > limit) {
            resolve(zipImg(fileFixed))
          } else {
            resolve(fileFixed)
          }
        }
      }
    } else {
      resolve(file)
    }
  })
}

// base64转图片
export function dataURLtoFile(dataurl, filename, mime) {
  return new Promise(resolve => {
    let arr = dataurl.split(";base64,")
    let suffix = mime.split("/")[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    let name = filename.split(".")[0]
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    let data = new File([u8arr], `${name}.${suffix}`, {
      type: mime
    })
    resolve(data)
  })
}
//`${filename}.${suffix}`
调用方法
const data = await zipImg(file,1024)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CC_Waiting

我,大学未工作,感谢您的打赏

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

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

打赏作者

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

抵扣说明:

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

余额充值