js压缩base64图片

今天试了用js把base64编码格式的图片进行压缩,记录一下:

base64图片转换地址 

base64图片转换网址

 代码如下

js:

$(document).ready(function(){

  compressImg(targetObj.src, 0.5, useImg, targetObj)
});


let targetObj = {

    // base64字符串 太大了,删掉了,可以自己替换
  src: ''
}
function compressImg (base64, multiple, useImg, targetObj) {
  // 第一个参数就是需要加密的base65,
  // 第二个是压缩系数 0-1,
  // 第三个压缩后的回调 用来获取处理后的 base64
  if (!base64) {
    return
  }
  // const _this = this
  const length = base64.length / 1024
  // 压缩方法
  let newImage = new Image()
  let quality = 0.6    // 压缩系数0-1之间
  newImage.src = base64
  newImage.setAttribute('crossOrigin', 'Anonymous') // url为外域时需要
  let imgWidth,
      imgHeight
  let w = undefined
  newImage.onload = function () {
    // 这里面的 this 指向 newImage
    // 通过改变图片宽高来实现压缩
    w = this.width * multiple
    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
      // quality 设置转换为base64编码后图片的质量,取值范围为0-1  没什么压缩效果
      // 还是得通过设置 canvas 的宽高来压缩
      quality = 0.6
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height) //  // 这里面的 this 指向 newImage
    let smallBase64 = canvas.toDataURL('image/jpeg', quality) // 压缩语句
    // 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间,请加以下语句,quality初始值根据情况自定
    // while (smallBase64.length / 1024 > 150) {
    // quality -= 0.01;
    // smallBase64 = canvas.toDataURL("image/jpeg", quality);
    // }
    // 防止最后一次压缩低于最低尺寸,只要quality递减合理,无需考虑
    // while (smallBase64.length / 1024 < 50) {
    // quality += 0.001;
    // smallBase64 = canvas.toDataURL("image/jpeg", quality);
    // }

    // 必须通过回调函数返回,否则无法及时拿到该值,回调函数异步执行
    console.log(`压缩前:${length}KB`)
    console.log(`压缩后:${smallBase64.length / 1024} KB`)


    useImg(smallBase64, targetObj)
  }
}
function useImg (base64, targetObj) {
  // targetObj 通过值引用的特性  用处理后的 base64 覆盖 处理前的 base63
  console.log('压缩后的 base64 :', base64)
  $("#img").attr("src",  base64);
  targetObj.src = base64
}


html 




    
    Title
    





     

测试

测试效果

js压缩base64图片_第1张图片

 压缩包已经上传资源包中,有需要可以下载,下完即用

你可能感兴趣的:(工作中,javascript,前端,开发语言)