SOURCE

/**
 * file 对象转 base64
 * @param {File} file
 * @returns
 */
export function setFileToBase64(file) {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    let reader = new FileReader()
    reader.onloadend = (e) => resolve({ file, result: e.target.result })
    reader.onerror = (err) => reject(err)
    reader.readAsDataURL(file)
    // #endif
  })
}

/**
 * base64 对象转 file
 * @param {string} base64
 * @param {File} file 原生file对象
 * @returns
 */
export function setBase64ToFile(base64, file) {
  const buffer = atob(base64.split(',')[1])
  let length = buffer.length
  const bufferArray = new Uint8Array(new ArrayBuffer(length))
  while (length--) {
    bufferArray[length] = buffer.charCodeAt(length)
  }
  return new File([bufferArray], file.name, { type: 'image/jpeg' })
}

/**
 * 压缩file图片文件
 * @param {File} file 图片文件
 * @param {number} limitSize 设置压缩大小
 * @param {number} quality 压缩质量 0-1之间,低于0.2会模糊图片
 * @returns
 */
export async function setFileCompressImg(file, limitSize = 4, quality = 0.5) {
  console.log('压缩中==================>', file, limitSize, quality)
  let size = limitSize * 1024 * 1024
  if (file.size <= size) return setFileToBase64(file)

  let res = await compressImg(file, quality)
  if (res.file.size <= size) {
    console.log('压缩成功===============>', res, res.file.size, size)
    return res
  }
  // 每次向下压缩缩减图片质量
  let q = Number((quality - 0.1).toFixed(2))
  return await setFileCompressImg(res.file, limitSize, q)
}

/**
 * 压缩文件
 * @param {File} file 图片文件
 * @param {number} quality 压缩质量 0-1之间,低于0.2会模糊图片
 * @returns
 */
export function compressImg(file, quality = 0.5) {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    let reader = new FileReader()
    reader.onloadend = (e) => {
      let image = new Image()
      image.onload = () => {
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height)
        // 压缩图片的核心方法:toDataURL
        let canvasUrl = canvas.toDataURL('image/jpeg', quality)
        const miniFile = setBase64ToFile(canvasUrl, file)
        resolve({ file: miniFile, result: canvasUrl })
      }
      image.src = e.target.result
    }
    reader.onerror = (err) => reject(err)
    reader.readAsDataURL(file)
    // #endif
  })
}
console 命令行工具 X clear

                    
>
console