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


微信小程序图片压缩功能的实现方法 :1、在 wx.chooseImage 接口选择相机图片。2、在 wx.getImageInfo 接口获取图片信息。3、计算压缩比例和最终图片的长宽。4、创建 canvas 绘制最终图片。5、在 wx.canvasToTempFilePath 接口将画布内容导出为图片并获取图片路径。

具体操作步骤:

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

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

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

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

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

代码实现如下所示:

wxml 文件

<canvascanvas-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压缩图片--------------

varratio=2;

varcanvasWidth=res.width//图片原始长宽

varcanvasHeight=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

})

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

varctx=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)

},

})

}

})


上一篇:mysql不知道root密码怎么登录

下一篇:mysql怎么取消root密码设置


微信小程序
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器