vue图片压缩

1.使用插件

    1.image-conversion

     1.1安装

npm i image-conversion --save

     1.2使用

//引用
import * as imageConversion from 'image-conversion'

//使用(主要方法)

//压缩到指定大小
beforeAvatarUpload(file) {
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
		const isLt2M = file.size / 1024 / 1024 < 2;
		if (!isJpgOrPng) {
			//自己封装的错误提示方法
			this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
		}
		if (!isLt2M) {
			this.$message.error('上传图片大小不能超过 2MB!');
		}
		if (!isLt2M || !isJpgOrPng) {
			return false;
		}
		return new Promise((resolve) => {
			// 压缩到100KB,这里的100就是要压缩的大小,可自定义
			imageConversion.compressAccurately(file, 100).then(res => {
				resolve(res);
			});
		})
}

//质量为0.6进行压缩

return new Promise((resolve) => {
    imageConversion.compress(file, 0.6).then((res) => {
        resolve(res)
    })
})

2.base64图片压缩

let targetObj = {
    // 51.4kb
    src: ''//自己的base64文件
}
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)
      targetObj.src = base64 
 }

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

3.二分法实现(与base64图片压缩原理相同 )

function compressPic(file, size, device) {
    const reader = new FileReader() // 创建 FileReader
    reader.readAsDataURL(file)
    reader.onload = ({ target: { result: src } }) => {
         const image = new Image() // 创建 img 元素
         image.src = src
         const canvas = document.createElement('canvas') // 创建 canvas 元素 
         image.onload = () => {
              canvas.width = image.width
              canvas.height = image.height
              canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height) // 绘制 图片到canvas上
              let canvasURL, nearFile // 创建变量 图片的file 最接近目标大小的file
              let pointDirection = true // 设置默认的二分方向 true为加二分值 false为减二分值
              let quality = 0
              for (let i = 1; i <= device; i++) {
                   canvasURL = canvas.toDataURL(file.type, pointDirection ? (quality += 1 / (2 ** i)) : (quality -= 1 / (2 ** i)))
                   let blob = dataURLtoBlob(canvasURL) // 此方法为base64转化为blod方法 见上方
                   miniFile = blobToFile(blob, 'new' + file.name, file.type) // 此方法为blod转file方法
                   // 上方调用的两个方法  dataURLtoBlod和blobToFile已经更新到下方文章中 可拿来直接使用
              }
              return miniFile
          }
     }
}

base64转blob

图片file转base64编码

图片url转base64编码

blob转file​​​​​​​

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值