【微信小程序利用Canvas 2D 接口实现图片等比例压缩(附源码)】

微信小程序利用Canvas 2D 接口实现图片等比例压缩(附源码)

图片上传到后台服务器,如果图片过大,就是导致上传时间长、占据内存大,利用微信小程序官方压缩图片接口(wx.compressImage)一容易导致图片失真;二ios系统不支持png格式图片压缩;其次就是压缩质量数值过大,根本满足不了压缩图片大小的要求,所以利用官方Canvas 2D接口压缩图片。
源码如下,经过调试,可以直接复用,有问题可以指出来,互相交流。

* wxml代码*

因为引用canvas组件只是为了实现图片压缩,所以不在页面上展示

<canvas type="2d" id="canvas_compress" style="width: {{canvasCompresswidth}}px; height: {{canvasCompressheight}}px;position: absolute; z-index: -1; left: -10000rpx;top: -10000rpx;" />

js代码*

Page({
  /** 页面的初始数据 */
  data: {
    ImageUrl:"/weixin/add.png",
    canvasCompresswidth:"",
    canvasCompressheight:"",
    imgPath:"",
    pathImage:"",
   }
  UpHeadImage:function(){
    const _this = this;
    wx.chooseMedia({//选择照片
      count:1,//选择照片数量
      mediaType:['image'],//只能上传图片
      sourceType:['album','camera'],//可通过相册或者照相机上传
      success:(res)=>{
        console.log("1、图片上传结果",res)
        let imgPath = res.tempFiles[0].tempFilePath;
        this.setData({
          imgPath:imgPath
        })
        console.log('图片临时地址',this.data.imgPath)
        wx.getImageInfo({//获取照片信息
          src:imgPath,
          success(res){
            console.log("2、图片信息",res)
            let width=res.width;
            let height=res.height;
            while( width > 720 || height > 960){//如果照片分辨率高>960或者宽>720进行等比例压缩,可以根据自己需要进行修改
              if(width>720){
                const ratio=width/720;
                width=720;
                height=height/ratio;
              }else if(height>960){
                const ratio=height/960;
                height=960;
                width=width/ratio;
              }
            }          
            _this.setData({
              canvasCompresswidth:width,
              canvasCompressheight:height
            })
            console.log("canvas的宽高",_this.data.canvasCompresswidth,_this.data.canvasCompressheight)//canvas宽高
            wx.createSelectorQuery()
              .select('#canvas_compress')
              .fields({node:true,size:true})
              .exec((res)=>{
                console.log("canvas对象",res)
                // Canvas 对象
                const canvas=res[0].node;
                // Canvas 绘制上下文
                const ctx =canvas.getContext('2d');
                // 初始化画布大小
                const dpr = wx.getSystemInfoSync().pixelRatio;
                canvas.width = width * dpr;
                canvas.height = height * dpr;
                ctx.scale(dpr,dpr);        
                const image =canvas.createImage();//进行绘图
                image.src= _this.data.imgPath;
                image.onload=()=>{
                  ctx.drawImage(image,0,0,width,height);
                  wx.canvasToTempFilePath({//生成图片
                    canvas:canvas,
                    destWidth:width,
                    destHeight:height,
                    fileType:'jpg',//绘制图片输出格式
                    success:(res)=>{
                      /***
                        将绘制的图片上传到后台服务器       
                      **/        
                    },
                    fail(error){
                      console.log('生成图片出错了!',error)
                    }
                  })
                }
              })
          },
          fail(res){
            console.log("错误信息",res)
          }
        })
      }
    })
  },
})

图片信息绘制前后对比
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值