随笔 - 502  文章 - 1 评论 - 6 阅读 - 37万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

1
复制代码
/**
 * 压缩图片
 * base64   : 图片base64字符串
 * w        : 图片宽高最大值
 * callback : 回调函数
 * quality  : 压缩系数0-1之间, 默认0.92
 * limit    : 压缩限制字符串长度单位(KB)
 * 使用:
 * import { compressBase64 } from '@/utils'
 * compressBase64(原base64, 1000, async (base64) => {
 *    console.log(base64.length)
 * })
 */
export function compressBase64 (base64, w, callback, quality = 0.92, limit = 500) {
  let newImage = new Image()
  newImage.src = base64
  newImage.setAttribute('crossOrigin', 'Anonymous')
  let imgWidth, imgHeight
  newImage.onload = function () {
    imgWidth = this.width
    imgHeight = this.height
    let canvas = document.createElement('canvas')
    let ctx = canvas.getContext('2d')
    if (Math.max(imgWidth, imgHeight) > w) {
      if (imgWidth > imgHeight) {
        canvas.width = w
        canvas.height = w * imgHeight / imgWidth
      } else {
        canvas.height = w
        canvas.width = w * imgWidth / imgHeight
      }
    } else {
      canvas.width = imgWidth
      canvas.height = imgHeight
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
    // 压缩语句
    // let base64 = canvas.toDataURL('image/jpeg', quality)
    // 如想确保图片压缩到自己想要的尺寸,500字符长度以下,请加以下语句, quality初始值根据情况自定
    let times = 0
    while (base64.length / 1024 > limit) {
      // quality -= 0.01
      base64 = canvas.toDataURL('image/jpeg', quality)
      // 限制3次,防止死循环
      if (times >= 3) {
        console.log('compress times >= 3, break')
        break
      }
      times = times + 1
    }
    // 回调函数返回,否则无法及时拿到该值
    callback(base64)
  }
}
复制代码

 

posted on   1161588342  阅读(248)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-02-16 POI 插入图片到Excel中
点击右上角即可分享
微信分享提示