美文网首页
uni-app 中如何实现图片转Base64

uni-app 中如何实现图片转Base64

作者: 酷酷的凯先生 | 来源:发表于2021-04-07 18:17 被阅读0次

前言

APP 开发中,或是 H5 开发时,避免不了会上传一写图片。这时一般有两种方式,利用 uni-app 中的 uni.uploadFile(OBJECT),这种方式比较简单,按照文档一步一步操作即可。有时后端接口要求我们上传时,图片必须是 Base64 格式的。也尝试了很多办法,结果都不大理想。今天介绍一下 image-tools 工具,可用于 uni-app、微信小程序、5+APP、浏览器(需允许跨域)

使用步骤

其实使用起来很简单,就三步:
第一步: 安装

npm i image-tools --save

第二步:引入

npm i image-tools --save
或者下载后按包引入
// 以下路径需根据项目实际情况填写
import { pathToBase64, base64ToPath } from '../../js/image-tools/index.js'

第三步:使用

pathToBase64
从图像路径转换为base64,uni-app、微信小程序和5+APP使用的路径不支持网络路径,
如果是网络路径需要先使用下载API下载下来。

pathToBase64(path)
    .then(base64 => {
        console.log(base64)
    })
    .catch(error => {
        console.error(error)
    })

base64ToPath
将图像base64保存为文件,返回文件路径。

base64ToPath(base64)
    .then(path => {
        console.log(path)
    })
    .catch(error => {
        console.error(error)
    })

多并发使用优化

可以利用promise来串行和并行的执行多个任务

// 并行
Promise.all(paths.map(path => pathToBase64(path)))
  .then(res => {
    console.log(res)
    // [base64, base64...]
  })
  .catch(error => {
    console.error(error)
  })
// 串行
paths.reduce((promise, path) => 
  promise.then(res => pathToBase64(path).then(base64 => (res.push(base64), res))), Promise.resolve([]))
  .then(res => {
    console.log(res)
    // [base64, base64...]
  })
  .catch(error => {
    console.error(error)
  })

小伙伴们记得点赞收藏哦~~~

相关文章

网友评论

      本文标题:uni-app 中如何实现图片转Base64

      本文链接:https://www.haomeiwen.com/subject/czbukltx.html