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'));
};
})
},
uniapp选取图片并转为base64
最新推荐文章于 2024-08-02 02:49:23 发布