Linux 拨号vps windows公众号手机端

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

lewis 7年前 (2018-09-28) 阅读数 10 #VPS/云服务器
文章标签 微信小程序

微信小程序图片压缩功能的实现方法 :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)

},

})

}

})


版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门