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

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

javascript 复制代码
 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及以上

javascript 复制代码
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

javascript 复制代码
Taro.getFileSystemManager().readFileSync(path, 'base64')

h5临时file转base64

javascript 复制代码
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

javascript 复制代码
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大小

javascript 复制代码
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

javascript 复制代码
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)
    }
  })
}
相关推荐
我想学LINUX2 个月前
【常见开源库的二次开发】基于openssl的加密与解密——Base的编解码(二进制转ascll)(二)
开源·嵌入式·base64·openssl·系统开发·base16·解编码
梦醒三叹2 个月前
Base64文件流查看下载PDF方法-CSDN
pdf·base64
我叫白小猿2 个月前
【常用知识点-Java】Springboot上传Excel并存放到本地
java·开发语言·spring boot·excel·上传
tekin3 个月前
Base64 编码表 参考
base64·编码·base64编码表
weixin_468466853 个月前
离线html文件及资源文件夹转换为单个mhtml文件
python·html·base64·mhtml·quoted-print·文件格式转换·文件存档
Echoo华地4 个月前
从CSV到数据库(简易)
数据库·oracle·上传·csv·导入·jdbctemplate
任磊abc4 个月前
前端加密的方式汇总
前端·哈希算法·base64·非对称加密·md5·对称加密·前端加密
DTcode74 个月前
微信小程序中的图像奥秘:图片与Base64的华丽变身记
微信小程序·小程序·base64
满地都是六便士他却抬头看向了月亮8 个月前
将项目上传到github
git·github·上传
a_靖8 个月前
阿里云OSS上传视频,可分片上传
上传·分片上传·上传视频·oss上传文件·oss分片上传