最近在做“闪送猫”项目,因为我们有一个需要用户提交图片和文字的功能,在审核小程序的时候被打回来了。需要做一个文字和图片的安全识别。本来腾讯提供了相关接口,只需要调用就行了。但是在使用中又出现了很对坑。特别记录一下。
1.压缩图片
今天是2020年9月17日23:46:52,不能使用腾讯自带的压缩图片功能。容易出现反效果,把图片压大。
2.接口限制
大小不能大于1m,并且上传buffer速度很慢。需要压缩到很小才能正常调用。
完成方案
//压缩图片 path是图片路径
compressImgs(path) {
var that = this
// 获得原始图片大小
wx.getImageInfo({
src: path,
success(res) {
// console.log ('获得原始图片大小',res.width)
//console.log (res.height)
var originWidth, originHeight;
originHeight = res.height;
originWidth = res.width;
console.log(originWidth, "originWidth");
// 压缩比例
// 最大尺寸限制
var maxWidth = 300,
maxHeight = 150;
// 目标尺寸
var targetWidth = originWidth,
targetHeight = originHeight;
// 等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 要求宽度*(原生图片比例)=新图片尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
// 更新 canvas 大小
that.setData({
cw: targetWidth,
ch: targetHeight
});
// 尝试压缩文件,创建 canvas
var ctx = wx.createCanvasContext('firstCanvas');
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(path, 0, 0, targetWidth, targetHeight);
setTimeout(function(){
ctx.draw(false, function () {
// 获得新图片输出
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 50,
height: 50,
destWidth: 50,
destHeight: 50,
quality:0.5,
canvasId: 'firstCanvas',
success: (res) => {
// 写入图片数组
console.log(res, "canva");
that.setData({
compressImg: res.tempFilePath
})
},
fail: (err) => {
console.error(err)
}
}, this)
});
},600)
},
})
},
Comments | NOTHING