<canvas canvas-id="myCanvas" style="width: 727px; height:1024px;"></canvas>
<u-button type='success' circle="shape" @click="upload">拍照</u-button>
<u-button type='primary' circle="shape" @click="uploadImg">上传</u-button>
upload() {
var _self = this;
uni.chooseImage({
count: 1,
sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], //从相册、相机选择
camera: "front", //拍照摄像头
success: function(res) {
console.log(res);
const tempFilePaths = res.tempFilePaths;
_self.getCut(tempFilePaths[0])
},
error: function(e) {
console.log(e);
}
});
},
getCut(fileImg) {
try {
var _self = this;
const ctx = uni.createCanvasContext('myCanvas');
const twoInchWidth = 727;
const twoInchHeight = 1024;
uni.getImageInfo({
// 图片加载完成后的操作
src: fileImg,
success: function(image) {
const x = (image.width - twoInchWidth) / 2;
const y = (image.height - twoInchHeight) / 2;
if (x < 0 || y < 0 || x + twoInchWidth > image.width || y + twoInchHeight > image
.height) {
console.error('裁切区域超出图片边界');
return;
}
ctx.drawImage(fileImg, x, y, twoInchWidth, twoInchHeight, 0, 0, twoInchWidth,
twoInchHeight);
ctx.draw(true, () => {
// 绘制完成后的操作
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
fileType: 'jpg',
success: function(res) {
console.log(res); // 这是转换后的图片路径
// 使用这个路径将图片上传到服务器
_self.miniImg(res.tempFilePath)
},
fail: function(error) {
console.error('导出图片失败:', error);
}
});
});
},
fail: function(error) {
console.error('获取图片信息失败:', error);
}
})
} catch (e) {
console.log(e);
//TODO handle the exception
}
},
miniImg(img) {
let _self = this
uni.saveImageToPhotosAlbum({
filePath: img,
success: function(res) {
console.log('save success', res);
// 转为网图
_self.getUpload(res.file)
}
});
},
getUpload(img) {
var _self = this;
uni.uploadFile({
url: BASE_URL + "api/images",
filePath: img,
name: "file",
formData: {
"type": "avatar"
},
success: function(res) {
console.log("网图", res);
_self.imglist =res.data
}
})
},
uploadImg() {
// 功能:只可上传一次,还未添加
if (this.imglist) {
uni.request({
url: BASE_URL + "api/door/uploadFacePhoto",
method: "POST",
data: {
esc_id: this.arr[0].esc_id,
student_code: this.arr[0].student_code,
photo: this.imglist
},
success: (res) => {
console.log(res)
if (res.data.code == 200) {
console.log("成功")
this.message = "上传成功"
this.type = "success"
setTimeout(() => {
this.$refs.wan.showToast();
this.flag = true
})
}
}
})
} else {
this.message = "请先拍照"
this.type = "error"
setTimeout(() => {
this.$refs.wan.showToast();
})
}
},