vue3+ts 中实现压缩图片、blob 转 base64

压缩图片

1.npm 安装 image-compressor.js

2.引入 import ImageCompressor from 'image-compressor.js'

3.使用

const compressImage = async (file: any) => {
  var imageCompressor = new ImageCompressor()
  return new Promise((resolve, reject) => {
    imageCompressor
      .compress(file, { quality: 0.8, maxHeight: 100, maxWidth: 100 })
      .then((result) => {
        resolve(result)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

// 这个方法是异步的,使用时记得
const afterRead = async (res: any) => {
     let file = await compressImage(files)
}

blob 转 base64,(同样也是异步的)

const blobToBase64 = (blob: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => {
      resolve(reader.result)
    }
    reader.onerror = reject
    reader.readAsDataURL(blob)
  })
}

你可能感兴趣的:(vue3,vue.js,前端框架,前端,typescript,vue)