图片转base64

源:https://github.com/zhetengbiji/image-tools

  1. npm引入
npm i image-tools --save
import { pathToBase64, base64ToPath } from 'image-tools'
  1. 使用

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)
  })
  1. 提示
    可以利用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)
  })

你可能感兴趣的:(图片转base64)