2021SC@SDUSC
本次在上篇的基础上分析拍照上传是如何获取到签名的。
拍照上传也分为两步,首先进行图片拍照,然后能够对获得的图片进行预览,调节尺寸和清晰度。
首先进行页面初始化数据,tablist就是两步的状态选择,tabcur主要用于状态的转换,snap是摄像头的使用状态,preview表示获取了照片。
ata: {
TabList: [
{name: '1. 拍照'},
{name: '2. 预览上传'}
],
TabCur: 0,
Snap: false,
Preview: false,
img: '',
sourceKey: '',
calImg: '',
weight:50,
imgList: [],
},
上传图片到页面时,也需要从图片从临时路径中提取出来,具体的实现方法与上篇所说的上传到后端是一样的,不同的是本次是上传到微信页面中。因此不具体展示代码,详细可参考上篇。
定义判断步骤的方法,使用了一个简化的方法,意思是与if语句相同的,因为将tabcur定义为0或1,所以可以实现tabcur的转换。
NumSteps() {
this.setData({
TabCur: this.data.TabCur == this.data.TabList.length - 1 ? 0 : this.data.TabCur + 1
})
},
下面定义的方法也是获取事件的监听调整tabcur的值。
Navigate(e) {
var target = e.currentTarget.dataset.index;
if (target < this.data.TabCur){
this.setData({
TabCur: target
})
}
},
然后是定义照相的方法,首先获取相机实例,然后获取camera实时帧数据,将照片临时路径赋给img,将preview改为true,stop进行拍照结束停止监听。
TakePhoto() {
const ctx = wx.createCameraContext()
const listener = ctx.onCameraFrame((frame) => {
console.log(frame)
})
ctx.takePhoto({
quality: 'high',
success: (res) => {
console.log(res)
this.setData({
img: res.tempImagePath,
Preview: true
})
listener.stop({
success: (res) => {
console.log(res)
},
fail: (err) => {
console.log(err)
}
})
},
fail: (err) => {
console.log(err)
}
})
},
接下来就是获取图片信息,展示到微信界面中,插件库中的getImageInfo可以获取图片信息但网络图片需先配置download域名才能生效,drawImage可以将图像绘制到画布中,它具有三个版本的写法都可以使用,draw将之前在绘图上下文中的描述画到canvas中,canvasPutImageData将像素数据绘制到画布,canvasToTempFilePath将当前画布指定区域的内容导出生成指定大小的图片。
RemoveBackground(){
const ctx = wx.createCanvasContext("myCanvas");
var that = this;
wx.getImageInfo({
src: this.data.img,
success: function (res) {
console.log(res)
ctx.drawImage(that.data.img, 0, 0, res.width, (res.width / 1080) * 960, 0, 0, 1080, 960);
ctx.draw(false, () => {
wx.canvasGetImageData({
canvasId: "myCanvas",
x: 240,
y: 221,
width: 600,
height: 600,
success: (res) => {
console.log(res)
var length = 600 * 300 * 4;
var calData = new Uint8ClampedArray(length)
var weight = that.data.weight / 50
for(var i = 0; i < length; i++){
calData[i] = (i % 4 === 3 ? 255 : (255 - (res.data[i + length] - res.data[i])) * 2 - (188 * weight));
}
wx.canvasPutImageData({
canvasId: "myCanvas2",
data: calData,
x: 0,
y: 0,
width: 600,
height: 300,
success: (res) => {
console.log(res)
wx.canvasToTempFilePath({
width: 600,
height: 300,
canvasId: "myCanvas2",
success: function(res) {
console.log(res)
that.setData({
calImg: res.tempFilePath,
})
}
});
},
fail: res => {
console.log(res)
},
})
},
fail: res => {
console.log(res)
},
})
})
}
})
}