父组件:
引入子组件
<prompPhoto :showPhoto="showPhoto" :photoOptions="photoOptions"></prompPhoto>
方法接受子组件传过来的压缩图片路径 从而对头像进行修改
changePhoto(){
let _this = this;
this.showPhoto = true;
this.photoOptions = {
//隐藏弹出框
change(){
_this.showPhoto = false;
},
// 图片上传成功
success(res){
_this.showPhoto = false;
_this.prePhoto = true;
_this.previewPhoto = res;
console.log('上传图片路径',res)
updateImgAPI({
filePath:res,
formData:{
'memberid':_this.userId,
},
name:'pic'
}).then( res => {
console.log(res)
})
}
}
},
子组件:
选择相册还是相机,canvas进行图片压缩
//从相册选择图片
albumPhoto(){
this.uploadPhoto('album')
},
cameraPhoto(){
this.uploadPhoto('camera')
},
uploadPhoto(type){
let self=this;
uni.chooseImage({
count:1,
sizeType: ['compressed'],
sourceType:[type],
success:(res)=>{
uni.getImageInfo({
// src: "https://c-ssl.duitang.com/uploads/item/201902/10/2019021070014_nPVJc.thumb.700_0.png",
src:res.tempFilePaths[0],
success: function(image) {
console.log("图片宽度:",image);
console.log("图片高度:",image.height);
let canvasWidth = image.width //图片原始长宽
let canvasHeight = image.height;
let base = canvasWidth/canvasHeight;
/* debugger */
if(canvasWidth>400){
canvasWidth = 400;
canvasHeight = Math.floor(canvasWidth/base);
}
console.log(11111,canvasHeight)
let img = document.createElement('img');
img.src = res.tempFilePaths[0]; // 要压缩的图片
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// 将图片画到canvas上面 使用Canvas压缩
console.log('图片1111',img)
ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
canvas.toBlob(function (fileSrc) {
let imgSrc = window.URL.createObjectURL(fileSrc);//原生JS生成文件路径
console.log('压缩完图片路径',imgSrc)
res.tempFilePaths && self.photoOptions.success(imgSrc)
});
},fail(err) {
console.log("读取图片失败:", err)
}
});
}
})
}