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

最近做一个小程序 上传图片时进行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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值