关于小程序压缩图片

411 阅读1分钟

2.9图片压缩

步骤:选择图片--图片转画布--画布变jpg--上传图片

相关Api:uni.chooseImage  wx.getImageInfo  wx.canvasToTempFilePath

HTML

<canvas canvas-id='photo_canvas' class='myCanvas' :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>

CSS

.myCanvas{
        position: absolute;
        left:-1000px;
        top:-1000px;
}
data(){
    return {
        canvasWidth:"",
        canvasHeight:"",
    }
}
onLoad() {
    //如果没有初始化会导致图片按照canvas原始数据裁剪
    this.canvasWidth=wx.getSystemInfoSync().windowWidth*2
    this.canvasHeight=wx.getSystemInfoSync().windowHeight*10
}
methods: {
    //选择图片
    chooseImage(index,pname) {
        var that = this;
        uni.chooseImage({
            count: 1, //默认9
            sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], //从相册选择、摄像头
            success: function(res) {
                for (let i = 0; i < res.tempFilePaths.length; i++) {
                    that.compressImg(res.tempFilePaths[i])
                }
            }
        });
    },
    // 压缩图片
    compressImg(imgpath){
        var that = this;
        console.log("2待压缩的图片",imgpath);
        this.canvasWidth=wx.getSystemInfoSync().windowWidth*2
        this.canvasHeight=wx.getSystemInfoSync().windowHeight*10
        // console.log("画布的长",this.canvasWidth,"画布的高",this.canvasHeight);
        wx.getImageInfo({
              src: imgpath,
              success (res) {
                var ctx = wx.createCanvasContext('photo_canvas'); // 创建画布
                // 清空画布
                ctx.clearRect(0, 0, that.canvasWidth, that.canvasHeight);
                ctx.draw(true);
                var towidth = that.canvasWidth;  //设置canvas尺寸,
                var toheight = that.canvasWidth*res.height/res.width;//根据图片比例换算出图片高度
                that.canvasHeight=toheight
                console.log("3eeeeeeeeeeeeee",that.canvasHeight);
                //console.log("图片宽度",res.width,"图片高度",res.height,"画布宽度",towidth,"画布高度",toheight);
                ctx.drawImage(imgpath, 0, 0, res.width, res.height, 0, 0, towidth, toheight);
                ctx.draw(false, function () {
                  wx.canvasToTempFilePath({
                        x:0,
                        y:0,
                        height:toheight,
                        canvasId: 'photo_canvas',
                        fileType:"jpg",
                        quality: 1,
                        success: function (res) {
                            console.log("4压缩的图片",res.tempFilePath);
                            //上传图片
                    }
                  }, this)
                })
            }
        })
    },
}

坑:每次压缩图片前确保canvas长度足够,即需要初始化canvas高度

  • this.canvasWidth=wx.getSystemInfoSync().windowWidth×2 this.canvasHeight=wx.getSystemInfoSync().windowHeight×10