uniApp将本地图片转base64格式

比如说,你将图片放在static文件夹中,那样我们该如何去转为base64格式呢?
我百度了一些方法,发现有一个uniApp插件专门去将图片转base64格式

插件:插件传送门

1.首先我们安装这个插件
在这里插入图片描述
2.然后在项目中找到插件的文件夹引入到需要的页面里面

import { pathToBase64, base64ToPath } from '../../js/image-tools/index.js'
每个人的安装的地方不同,找到image-tools/index.js就行,然后引入

3.下面就可以使用了
该如何使用呢,插件下面文档是这样写的
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)
  })

看你们的需求是什么,然后针对的使用,切记图片的路径不是…/…/xx/xx,而是/static/xx

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值