钉钉图片压缩
公司有前端上传图片压缩的需求,切在钉钉前端做,可减少网络带来的影响,但是框架中钉钉自带的图片压缩无效,不知道是SDK版本问题还是平台问题,所以自己研究压缩。
研究过程中发现无法使用一些通用的js,比如new Image()对象,无法使用它的img.onload()方法。所以另辟蹊径:
使用uniapp编译后做修改,可行。
页面:
首先需要创建一个画布,用来输出
<view hidden="{{canvasHidden}}" style="width: 20px;height: 20px">
<canvas style="{{'width:'+(cWidth+'px')+';'+('height:'+(cHeight+'px')+';')}}" id="canvas"></canvas>
</view>
js:
compressImage (t,selectImg) {
var n = this;
n.setData({
canvasHidden: false
})
dd.getImageInfo({
src: t,
success: function (t) {
console.log("get image info success",t);
var c = 2,
o = t.width,
a = t.height;
while (o > 1000 || a > 1000)
(o = Math.trunc(t.width / c)),
(a = Math.trunc(t.height / c)),
c++;
(n.cWidth = o), (n.cHeight = a);
console.log("width and height",n.cWidth,n.cHeight);
n.setData({
cWidth: o,
cHeight: a
});
var i = dd.createCanvasContext("canvas");
i.drawImage(t.path, 0, 0, o, a);
i.draw(
!1,
setTimeout(function () {
dd.canvasToTempFilePath({
canvasId: "canvas",
destWidth: o,
destHeight: a,
fileType: "jpg",
quality: 0.8,
success: function (t) {
console.log("canvas file",t),
// 上传图片到服务器
// .......
},
fail: function (e) {
console.log("draw error res.errMsg",e);
},
});
}, 2000) // 可多给点时间进行压缩
);
},
fail: function (e) {
console.log("get img info err.errMsg");
},
});
},
将这个图片传到后台后发现,压缩到了100k左右,也没有出现失真的情况。