微信小程序使用RenderingContext进行图片尺寸压缩

本文介绍了在微信小程序中如何解决高像素图片导致的上传超时和流量消耗问题。通过创建隐形canvas,调整图片尺寸并利用设备像素比实现物理像素与逻辑像素的匹配,从而达到有效压缩图片的目的。详细步骤包括设置canvas尺寸,利用drawImage方法绘制压缩后的图像,以及转换为base64进行上传。
摘要由CSDN通过智能技术生成

现在手机摄像头的像素越来越高,把很高像素的照片上传腾讯人脸识别,会发生超时错误,并且消耗了更多的网络流量。通常业务场景要上传的图片,像素要求也没那么高。

目前compressimage只实现了压缩算法的压缩质量调整,并没有改变图片的尺寸,因此,压缩也有限。

在网上查了相关文章,大部分基于老的CanvasContext处理的,现在小程序已经不支持了。

由于对前端程序没什么经验,只有不断问度娘和尝试,终于实现了图片尺寸压缩,分享给大家。

在尝试中发现关键点是,图像的物理像素和逻辑像素的关系,有的使用的逻辑像素,有点使用的物理像素。

具体处理如下:

首先在页面上建一个看不见的canvas:

  <canvas type="2d" id="myCanvas" style="width:{{cWidth}}px;height:{{cHeight}}px; position: absolute;left:-1000px;top:-1000px;"></canvas>

处理函数:

compressImg: function (imgFile) { //imgFile欲压缩的图片文件名和路径

    var that = this;

    console.log("compress start...");

    const query = wx.createSelectorQuery()

    query.select('#myCanvas')

      .fields({

        node: true,

        size: true

      })

      .exec(function (res) {

        const canvas = res[0].node;

        const ctx = canvas.getContext('2d');

        let image = canvas.createImage();

        image.src = imgFile;

        image.onload = function () {

          let styleWidth = image.width; //单位px

          let styleHeight = image.height; //单位px

          var sizeLimit = 200;  //单位px,逻辑像素,欲压缩到的最大边的px数

          if (Math.max(styleWidth, styleHeight) > sizeLimit) {

            var percent = sizeLimit / Math.max(styleWidth, styleHeight);

            styleWidth = Math.trunc(styleWidth * percent)

            styleHeight = Math.trunc(styleHeight * percent)

          }

          const dpr = wx.getSystemInfoSync().pixelRatio;  //获取设备像素比,物理像素和逻辑像素的比值

          //重点:DrawImage使用的物理像素,canvas的width、height一定要设置,否则,图像会变形。因为系统给的初始值和你图片的比例不一致

          canvas.width = styleWidth * dpr;

          canvas.height = styleHeight * dpr;

          //canvas实际显示的是style中的width和height,单位px

          that.setData({

            cWidth: styleWidth,

            cHeight: styleHeight

          });

          ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

//使用jpeg格式,比png要小一个数量级

          let dataURL = canvas.toDataURL("image/jpeg", 0.7);

          //自己后续处理,我直接上传base64编码就可以了;

        }

      })

  },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值