readFile会报错
onChooseImage() {
let that = this
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: function(res) {
let tempFilePaths = res.tempFilePaths[0]
// 图片转 base64
uni.getFileSystemManager().readFile({
filePath: tempFilePaths, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: v => { //成功的回调
let base64 = v.data // 返回的是没有 'data:image/jpeg;base64,'头的数据, 需要在页面显示图片可自行追加上
that.base64str = 'data:image/jpeg;base64,' + base64
}
})
}
});
}
2.建议用这个(可控制压缩系数)
onChooseImage() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
fail: () => {
this.$u.toast('选择照片失败')
},
success: (res) => {
let blob = res.tempFilePaths[0]
//获取blob
this.blobToBase64(blob, 300).then(res => {
console.log('base64=='+res)
})
}
})
},
blobToBase64(blob, wid) {
return new Promise((resolve, reject) => {
let image = new Image();
image.onload = function() {
let canvas = document.createElement('canvas');
var w = this.naturalWidth,
h = this.naturalHeight,
scale = w / h;
w = wid || w;
h = w / scale;
canvas.width = w
canvas.height = h;
// 将图片插入画布并开始绘制
canvas.getContext('2d').drawImage(image, 0, 0, w, h);
// result
let result = canvas.toDataURL('image/png')
resolve(result);
};
image.setAttribute("crossOrigin", 'Anonymous');
image.src = blob;
// 图片加载失败的错误处理
image.onerror = () => {
reject(new Error('urlToBase64 error'));
};
})
},