taro 支付宝/微信小程序/h5 上传 - base64的那些事儿

支付宝小程序临时path转base64 - 基础库2.0以下

 function getImageInfo(path) {
  return new Promise(resolve => {
    my.getImageInfo({
      src: path,
      success: res => {
        resolve(res)
      }
    })
  })
}
export async function getBase64InAlipay({ id, path }) {
  const { width, height } = await getImageInfo(path)
  let newWidth = width
  let newHeight = height
  let scale = 1
  if (width > height) {
    newWidth = width > 750 ? 750 : width
    scale = newWidth / width
    newHeight = parseInt(height * scale)
  } else {
    newHeight = height > 750 ? 750 : height
    scale = newHeight / height
    newWidth = parseInt(width * scale)
  }

  if (!ctx || (ctx && (newWidth !== canvasWidth || newHeight !== canvasHeight))) {
    ctx = Taro.createCanvasContext(id)
    canvasWidth = newWidth
    canvasHeight = newHeight
    events.trigger(PAGE_EVENTS.SET_CANVAS_SIZE, { width: newWidth, height: newHeight })
  }

  return new Promise(resolve => {
    ctx.drawImage(path, 0, 0, newWidth, newHeight)
    ctx.draw(false, () => {
      ctx.toDataURL().then(async dataURL => {
        resolve(dataURL)
      })
    })
  })
}

支付宝小程序临时path转base64 - 基础库2.0及以上

async function useGetBase64ByFileInAlipay({ path }) {
  return new Promise(resolve => {
    const fs = my.getFileSystemManager()
    fs.readFile({
      filePath: path,
      success: ({ data }) => {
        const base64 = my.arrayBufferToBase64(data)
        resolve(base64)
      }
    })
  })
}

微信小程序临时path转base64

Taro.getFileSystemManager().readFileSync(path, 'base64')

h5临时file转base64

export function getBase64ByFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    let fileResult = ''
    reader.readAsDataURL(file)
    reader.onload = () => {
      fileResult = reader.result
    }
    reader.onerror = error => {
      reject(error)
    }
    reader.onloadend = () => {
      resolve(fileResult)
    }
  })
}

h5 base64转file

function getFileByBase64(data, filename) {
  let arr = data.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {
    type: mime
  })
}

获取base64大小

function getBase64Size(base64Str) {
  const idx = base64Str.indexOf('base64,')
  if (idx < 0) return -1
  const str = base64Str.substr(idx + 6)
  return (str.length * 0.75).toFixed(2)
}

h5 压缩base64

function compressBase64(base64) {
  return new Promise(resolve => {
    let base64Url = base64
    if (!base64Url) {
      resolve('')
      return
    }
    let base64Size = getBase64Size(base64Url)
    const isExceed = base64Size / 1024 > 1024 * UPLOAD_FILE_SIZE_MAX
    if (!isExceed) {
      resolve(base64Url)
    }
    let canvas = document.createElement('canvas')
    let newImage = new Image()
    let quality = 0.95
    newImage.src = base64Url
    newImage.onload = function () {
      canvas.width = newImage.width
      canvas.height = newImage.height
      let ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height)
      base64Url = canvas.toDataURL('image/jpeg', quality)
        while (base64Size / 1024 > 1024 * UPLOAD_FILE_SIZE_MAX && quality * 100 > 5) {
        quality -= 0.05
        base64Url = canvas.toDataURL("image/jpeg", quality)
        base64Size = getBase64Size(base64Url)
      }
      if (base64Size / 1024 > 1024 * UPLOAD_FILE_SIZE_MAX) {
        useShowToast(`请上传小于${UPLOAD_FILE_SIZE_MAX}M的图片`)
        resolve('')
        return
      }
      resolve(base64Url)
    }
  })
}

你可能感兴趣的:(H5,#,Taro,小程序,上传,base64)