本文主要是介绍微信小程序利用canva进行大图片压缩,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
找了很多方法没找到合适的图片压缩第三方库,有没有推荐的微信小程序压缩图片的第三方库呀(有的话,互帮互助,感谢)
我自己写了个简易的压缩方法,其实就是等比例的缩小图片,并把png转为jpg,毕竟png的颜色太多。
wxml:
<canvas canvas-id="canvas" class="my-canvas" style="width:{{cWidth}}px;height:{{cHeight}}px">
</canvas>
js:
canvasCompress(obj, n) {let {tempFiles} = this.datalet _this = thisreturn new Promise((resolve, reject) => {let canvasWidth = obj.params.widthlet canvasHeight = obj.params.heightconsole.log(canvasWidth);let quality = 0.8if (canvasWidth > 750) {canvasWidth = 750canvasHeight = Math.trunc(obj.params.height * 750 / obj.params.width)quality = 0.5} else if (canvasWidth > 400 && canvasWidth < 749) {canvasWidth = 400canvasHeight = Math.trunc(obj.params.height * 400 / obj.params.width)quality = 0.6}this.setData({cWidth: canvasWidth,cHeight: canvasHeight})let ctx = wx.createCanvasContext('canvas')ctx.clearRect(0, 0, canvasWidth, canvasHeight);ctx.drawImage(tempFiles[n].tempFilePath, 0, 0, canvasWidth, canvasHeight)ctx.draw(false, _this.timer = setTimeout(function () {wx.canvasToTempFilePath({canvasId: 'canvas',destWidth: canvasWidth, // 输出图片的宽度destHeight: canvasHeight, // 输出图片的高度fileType: 'jpg', // 图片输出格式quality: 0.5, // 图片质量 0-1success: function (res) {clearTimeout(_this.timer)resolve(res.tempFilePath);},fail: function (res) {clearTimeout(_this.timer)reject(err.errMsg)}})}, 600)) //留一定的时间绘制canvas})},
这篇关于微信小程序利用canva进行大图片压缩的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!