温馨提示×

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

木子
661
2021-05-12 18:34:20
栏目: 云计算

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

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

            },

         })

    }

})


0