uniapp中根据图片路径(网络或本地路径)转换为base64

uniapp中根据图片路径(网络或本地路径)转换为base64

javascript 复制代码
/**
 * 图片地址转换为base64格式图片
 * @param {string} url 图片地址 可网络地址、本地相对路径
 * @param {string} type base64图片类型 默认png
 */
function urlToBase64(url, type = 'png') {
  let promises

  // 网络地址 或者h5端本地相对路径 可使用request方式
  promises = new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: 'GET',
      responseType: 'arraybuffer',
      success: (res) => {
        const base64 = `data:image/${type};base64,${uni.arrayBufferToBase64(res.data)}`
        resolve(base64);
      },
      fail: (err) => {
        reject(err);
      },
    })
  })

  // #ifdef APP
  if (!url.startsWith('http')) {
    // app真机本地相对路径
    promises = new Promise((resolve, reject) => {
      uni.compressImage({
        src: url,
        quality: 100, // 图片质量压缩0~100,100表示图片质量保持原样
        success: (res) => {
          const tempUrl = res.tempFilePath // 使用compressImage获取到安卓本地路径file:///...
          plus.io.resolveLocalFileSystemURL(tempUrl, (entry) => {
            entry.file((e) => {
              let fileReader = new plus.io.FileReader();
              fileReader.onload = (r) => {
                resolve(r.target.result)
              }
              fileReader.readAsDataURL(e)
            })
          })
        },
        fail: (err) => {
          reject(err);
        },
      })
    })
  }
  // #endif

  return promises
}
相关推荐
一只一只妖20 分钟前
uni-app + ts请求封装最佳实践(GET/POST + 加载态 + 错误兜底)
typescript·uni-app
2501_9160074717 小时前
苹果手机iOS应用管理全指南与隐藏功能详解
android·ios·智能手机·小程序·uni-app·iphone·webview
2501_9151063219 小时前
全面理解 iOS 帧率,构建从渲染到系统行为的多工具协同流畅度分析体系
android·ios·小程序·https·uni-app·iphone·webview
2501_9160088921 小时前
iOS 能耗检测的工程化方法,构建多工具协同的电量分析与性能能效体系
android·ios·小程序·https·uni-app·iphone·webview
济南壹软网络科技有限公司1 天前
综合社交服务平台的技术架构与实践:构建高可用、多端覆盖的互动生态
uni-app·php·开源源码·陪玩陪聊h5
2501_915921431 天前
重新理解 iOS 的 Bundle Id 从创建、管理到协作的工程策略
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 天前
当 altool 退出历史舞台,iOS 上传链路的演变与替代方案的工程实践
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张1 天前
Transporter 的局限与替代路径,iOS 上传流程在多平台团队中的演进
android·ios·小程序·https·uni-app·iphone·webview
lwprain1 天前
uniapp使用uniview-plus性能问题处理
uni-app
00后程序员张1 天前
Python 抓包工具全面解析,从网络监听、协议解析到底层数据流捕获的多层调试方案
开发语言·网络·python·ios·小程序·uni-app·iphone