点击上传图片
getCanvasImg 的第一个参数 从数组的第0个开始 第二个参数是计算不合法照片的个数的 暂时没用到 第三个参数是选择的图片的临时路径
// 上传图片
chooseImage: function (e) {
var _this = this
wx.chooseImage({
count: 9,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success(photo) {
_this.getCanvasImg(0, 0, photo.tempFilePaths); //进行压缩
}
})
},
//压缩并获取图片,这里用了递归的方法来解决canvas的draw方法延时的问题
getCanvasImg: function (index, failNum, tempFilePaths) {
var that = this;
if (index < tempFilePaths.length) {
wx.showLoading({
title: '检测图片中...',
mask: true
});
wx.getImageInfo({
src: tempFilePaths[index],
success: function (res) {
const ctx = wx.createCanvasContext('photo_canvas');
var picW = res.width,
picH = res.height;
ctx.drawImage(tempFilePaths[index], 0, 0, 100, parseInt(picH / picW * 100)) //按比例对图片进行画图
ctx.draw(false, function () {
//把画好的图 描下来,写成临时文件
wx.canvasToTempFilePath({
x: -200,
y: -200,
width: 100,
height: parseInt(picH / picW * 100),
destWidth: 100,
destHeight: parseInt(picH / picW * 100),
canvasId: 'photo_canvas',
success: function (res) {
var tmpfp = res.tempFilePath
wx.getFileSystemManager().readFile({
filePath: res.tempFilePath,
success: buffer => {
loginModel.sensitiveImg(buffer.data).then(imgRes => {
wx.hideLoading();
console.log(imgRes)
if (imgRes.result.errCode == 87014) {
wx.showToast({
title: '图片含有违法违规内容',
icon: 'none'
})
} else {
var tmpary = that.data.images;
tmpary.push(tmpfp);
that.setData({
images: tmpary
})
}
index += 1;
that.getCanvasImg(index, 0, tempFilePaths);
})
},
catch: err => {
wx.hideLoading();
index += 1;
that.getCanvasImg(index, 0, tempFilePaths);
console.log(err)
}
})
}
})
})
}
})
}
},
wxml页面也需要添加一段压缩用到的代码
<canvas canvas-id='photo_canvas' style='width:688rpx;height:{{canvas_h}}px;position:fixed;top:-9999px;' class='myCanvas'></canvas>
其中的方法sensitiveImg 是在model中封装的方法
然后 cloudfunctions 文件下的文字和图片检测我就不说了
//过滤敏感图片
sensitiveImg(img){
wx.cloud.init();
return wx.cloud.callFunction({
// 云函数名称
name: 'imgSecCheck',
// 传给云函数的参数
data: ({
content: img
}),
})
}
当图片检测正常的时候 放到展示的数组中 当云函数返回的errcode 为87014的时候 图片不合法 提示之后不做任何操作
这个问题困扰了好几天弄出来的
如有疑问欢迎提出