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​​​​​​​

相关推荐

  1. vue图片压缩

    2024-03-31 05:34:05       43 阅读
  2. vue2上传图片image-conversion压缩

    2024-03-31 05:34:05       51 阅读
  3. vue3上传图片,进行图片压缩(image-compressor.js)

    2024-03-31 05:34:05       26 阅读
  4. 封装图片压缩

    2024-03-31 05:34:05       26 阅读
  5. vue3 el-upload 自动上传前压缩图片的大小

    2024-03-31 05:34:05       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 05:34:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 05:34:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 05:34:05       82 阅读
  4. Python语言-面向对象

    2024-03-31 05:34:05       91 阅读

热门阅读

  1. RK3588平台开发系列讲解(开发环境搭建)

    2024-03-31 05:34:05       38 阅读
  2. springboot和spring的区别

    2024-03-31 05:34:05       35 阅读
  3. 预处理、编译、汇编、链接过程

    2024-03-31 05:34:05       37 阅读
  4. Superset二次开发之环境搭建Clickhouse(Linux版)

    2024-03-31 05:34:05       44 阅读
  5. npm 常用命令详解 详细

    2024-03-31 05:34:05       33 阅读
  6. vue时间组件:dayjs与moment

    2024-03-31 05:34:05       41 阅读
  7. 物联网在农业领域应用案例

    2024-03-31 05:34:05       43 阅读
  8. MySQL正则表达式的详细介绍

    2024-03-31 05:34:05       39 阅读
  9. 【力扣】191.位 1 的个数、485.最大连续 1 的个数

    2024-03-31 05:34:05       38 阅读