uniapp中临时图片地址转base64

新建js文件中写入


/**
 * 临时图片路径转base64
 * @param {Object} param 传一个对象,对象里包括
 * url: 临时图片存放路径,选择图片返回的相对路径
 * type: 图片类型,如:png
 */
export const imgBase64 = (url, type) => {
    return new Promise((resolve, reject) => {
        if (!!uni.getFileSystemManager()) {
            console.log(1, url, type)
            uni.getFileSystemManager().readFile({
                filePath: url, //选择图片返回的相对路径
                encoding: "base64", //编码格式
                success: (res) => {
                    console.log(2)
                    resolve(
                        "data:image/" +
                            type.toLocaleLowerCase() +
                            ";base64," +
                            res.data
                    );
                },
                fail: (res) => reject(res.errMsg),
            });
        } else {
            console.log(3)
            uni.request({
                url: url,
                method: "GET",
                responseType: "arraybuffer",
                success: (ress) => {
                    console.log(4)
                    let base64 = wx.arrayBufferToBase64(ress.data); //把arraybuffer转成base64
                    base64 = "data:image/jpeg;base64," + base64; //不加上这串字符,在页面无法显示的
                    resolve(base64);
                },
                fail: (res) => reject(res.errMsg),
            });
        }
    });
}

以上写法返回promise类型返回值,使用时注意接收方式

代码来源: https://zhuanlan.zhihu.com/p/540550727

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值