记微信小程序 利用canvas压缩图片 并进行base64

2,604 阅读1分钟

最近做一个小程序 上传图片时进行base64 总是报上传图片失败 究其原因是图片过大 需要进行压缩

废话不多说 上代码

选择图片后利用canvas重新绘制图片大小

利用绝对定位 隐藏canvas

 <image class="uploader_input_icon" src="/images/wy/uploader9@3x.png" />
 <canvas canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"></canvas>

因为这里有多处需要上传代码并压缩,所以抽取出来作为公共方法

const chooseImage = (_this) => {
    wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 指定只能为压缩图,首先进行一次默认压缩
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
        success: photo => {
        //将tempFilePaths[0]加入到images数组 作为展示
            _this.data.images.push(photo.tempFilePaths[0])

            _this.setData({
                    images: _this.data.images
                })
                //-----返回选定照片的本地文件路径列表,获取照片信息-----------
            wx.getImageInfo({
                src: photo.tempFilePaths[0],
                success: 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++;
                    }
                    _this.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: res => {
                                console.log(res.tempFilePath) //最终图片路径
                                let path = res.tempFilePath
                                let arr = path.split('.');
                                let list = {};
                                //获取图片类型
                                list.imageType = '.' + arr[arr.length - 1];
                                //对图片进行base64 获取base64Code
                                list.base64Code = wx
                                    .getFileSystemManager()
                                    .readFileSync(path, 'base64');
                                console.log(list, _this.data.images)
                                 //将list加入到imageList数组中 作为后台接口参数
                                _this.data.imageList.push(list)

                            },
                            fail: res => {
                                console.log(res.errMsg)
                            }
                        })
                    }, 100))
                }, //留一定的时间绘制canvas
                fail: res => {
                    console.log(res.errMsg)
                }
            })
        }
    })
}

module.exports = {
    chooseImage
}

使用时只需要引入

let uploader = require('../utils/uploader')


data:{
 images: [],
 imageList: []
}

//方法中使用
uploader.chooseImage(this)