首页>>帮助中心>>国内vps微信小程序图片压缩功能的实现方法

国内vps微信小程序图片压缩功能的实现方法

2023/6/14 391次

国内vps微信小程序图具体操作步骤:

1、通过 wx.chooseImage 接口选择相机图片。

2、通过 wx.getImageInfo 接口获取图片信息(长宽,类型)。

3、 计算压缩比例和最终图片的长宽。

4、创建 canvas 绘图上下文,绘制最终图片。

5. 通过 wx.canvasToTempFilePath 接口将画布内容导出为图片并获取图片路径。

代码实现如下所示:

wxml 文件

<canvas canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"></canvas>

js 文件

data:{ cWidth: 0; cHeight : 0;}

data:{ cWidth: 0; cHeight : 0;}

</pre>

<pre>

wx.chooseImage({

count: 1, // 默认9

sizeType: ['compressed'], // 指定只能为压缩图,首先进行一次默认压缩

sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有

success: function (photo) {

//-----返回选定照片的本地文件路径列表,获取照片信息-----------

wx.getImageInfo({

src: photo.tempFilePaths[0],

success: function(res){

//---------利用canvas压缩图片--------------

var ratio = 2;

var canvasWidth = res.width //图片原始长宽

var canvasHeight = res.height

while (canvasWidth > 400 || canvasHeight > 400){// 保证宽高在400以内

canvasWidth = Math.trunc(res.width / ratio)

canvasHeight = Math.trunc(res.height / ratio)

ratio++;

}

that.setData({

cWidth: canvasWidth,

cHeight: canvasHeight

})

//----------绘制图形并取出图片路径--------------

var ctx = wx.createCanvasContext('canvas')

ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)

ctx.draw(false, setTimeout(function(){

wx.canvasToTempFilePath({

canvasId: 'canvas',

destWidth: canvasWidth,

destHeight: canvasHeight,

success: function (res) {

console.log(res.tempFilePath)//最终图片路径

},

fail: function (res) {

console.log(res.errMsg)

}

})

},100)) //留一定的时间绘制canvas

fail: function(res){

console.log(res.errMsg)

},

})

}

})

购买使用一诺网络国内vps,可以极大降低初创企业、中小企业以及个人开发者等用户群体的整体IT使用成本,无需亲自搭建基础设施、简化了运维和管理的日常工作量,使用户能够更专注于自身的业务发展和创新。国内vps低至69/月,购买链接:https://www.enuoidc.com/vpszq.html?typeid=5