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)
    }
  })
}
相关推荐
QGC二次开发21 天前
Qt:图片文字转base64程序
开发语言·c++·qt·数据可视化·base64·编码
安红豆.1 个月前
特殊的 BASE64 1
ctf·base64·汇编语言·逆向工程
萧仁武1 个月前
【Vue】以RuoYi框架前端为例,ElementUI封装图片上传组件——将图片信息转成base64后提交到后端保存
vue·ruoyi·base64
我想学LINUX4 个月前
【常见开源库的二次开发】基于openssl的加密与解密——Base的编解码(二进制转ascll)(二)
开源·嵌入式·base64·openssl·系统开发·base16·解编码
梦醒三叹4 个月前
Base64文件流查看下载PDF方法-CSDN
pdf·base64
我叫白小猿4 个月前
【常用知识点-Java】Springboot上传Excel并存放到本地
java·开发语言·spring boot·excel·上传
tekin5 个月前
Base64 编码表 参考
base64·编码·base64编码表
weixin_468466855 个月前
离线html文件及资源文件夹转换为单个mhtml文件
python·html·base64·mhtml·quoted-print·文件格式转换·文件存档
Echoo华地5 个月前
从CSV到数据库(简易)
数据库·oracle·上传·csv·导入·jdbctemplate
任磊abc5 个月前
前端加密的方式汇总
前端·哈希算法·base64·非对称加密·md5·对称加密·前端加密