一、图片压缩
这API目前从小程序开发工具没法调试
得用真机调试
// 压缩开始
wx.compressImage({
src: tempFilePaths[0], // 图片路径
quality: 0, // 压缩质量
success: res => {
console.log("压缩前:", tempFilePaths[0])
console.log("压缩后:", res.tempFilePath)
},
fail: error => {
console.log("error", error)
}
});
// 压缩结束
二、图片上传和审核
方法一:把文件传到云存储,云函数根据fileID获取buffer(得及时删除文件)
小程序端js代码(负责图片上传):
console.log('my-image' + tempFilePaths[0].match(/\.[^.]+?$/)[0])
// 在此添加内容审核机制
wx.cloud.uploadFile({
cloudPath: 'my-image' + tempFilePaths[0].match(/\.[^.]+?$/)[0],
filePath: tempFilePaths[0],
success: res => {
wx.showToast({
icon: 'none',
title: '正在加载图片...',
})
console.log('上传成功:', res)
wx.cloud.callFunction({
name: 'checkImg',
data: {
contentType: 'image/jpg',
fileID: res.fileID
}
}).then(res => {
console.log("检测结果", res.result);
if (res.result.errCode == 0) {
this.setData({
bgPic: tempFilePaths[0],
picChoosed: true
});
} else {
this.setData({
bgPic: '../../image/ban.jpg',
picChoosed: true
});
wx.showToast({
icon: 'none',
title: '图片含有敏感信息,换张图吧~',
})
}
})
},
fail: e => {
console.error('上传失败:', e)
}
})
云函数checkImg:(云函数配置看这里)
// 云函数入口函数 图片下载和鉴别
exports.main = async(event, context) => {
const fileID = event.fileID
const res = await cloud.downloadFile({
fileID: fileID,
})
const buffer = res.fileContent
try {
var result = await cloud.openapi.security.imgSecCheck({
media: {
contentType: event.contentType,
value: buffer
}
});
return result
} catch (err) {
return err
}
}
方法二:小程序端图片转换base64,直接把buffer传到云函数处理(就是有点卡)
小程序端js:
// 审核开始
console.log("内容审核机制启动...");
console.log(res);
// 转base64
let base64 = wx.getFileSystemManager().readFileSync(res.tempFilePath, 'base64')
// console.log(base64)
// console.log("access_token =", this.data.accessToken);
console.log("图片地址 = ", tempFilePaths[0])
//调用云函数
wx.cloud.callFunction({
// 云函数名称
name: 'checkImg',
// 传给云函数的参数
data: {
contentType: 'image/jpg',
value: base64
},
})
.then(res => {
// this.setData({
// picPassed: res.result.pic_passed
// });
console.log("errCode: ", res.result.errCode);
console.log("errMsg: ", res.result.errMsg);
// 图片不合法
if (res.result.errCode == 87014) {
this.setData({
bgPic: '../../image/ban.jpg'
});
} else {
this.setData({
bgPic: tempFilePaths[0]
});
}
console.log('Img validation check: ', this.data.picPassed);
console.log('Original Img: ', tempFilePaths[0]);
})
.catch(console.error);
// 审核结束
云函数:
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async(event, context) => {
try {
console.log('check img...');
console.log('contentType :', event.contentType);
console.log('value :', Buffer.from(event.value));
var result = await cloud.openapi.security.imgSecCheck({
media: {
contentType: event.contentType,
value: Buffer.from(event.value)
}
});
return result
} catch (err) {
return err
}
}