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)
    }
  })
}
相关推荐
艾小逗18 小时前
uniapp将图片url转换成base64支持app和h5
uni-app·base64·imagetobase64
柳晓黑胡椒10 天前
cesiusm实现 多图例展示+点聚合(base64图标)
css3·canvas·base64·cesium·animation
上架ipa15 天前
ios打包文件上传App Store windows工具
上传·ios打包
QGC二次开发1 个月前
Qt:图片文字转base64程序
开发语言·c++·qt·数据可视化·base64·编码
安红豆.2 个月前
特殊的 BASE64 1
ctf·base64·汇编语言·逆向工程
萧仁武2 个月前
【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编码表