小程序图片压缩

小程序图片压缩

 压缩图片原地址https://my.oschina.net/u/3362856/blog/1162498

chooseImage: function (e) {//上传照片

  var that = this;

  wx.chooseImage({

    count:1,//最多可以选择的图片张数,默认9

    sizeType: [ 'compressed'], // 可以指定是原图还是压缩图,默认二者都有

    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有

    success: function (res) {

      // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片

      that.setData({

        files: res.tempFilePaths[0]

      });

    }

  })

},

drawCanvas:function(){// 缩放图片

  const ctx = wx.createCanvasContext('attendCanvasId');

  let that=this;

  wx.getImageInfo({

src: that.data.files,

    success:function (res) {

if(res.width>500||res.height>500){//判断图片是否超过500像素

        let scale=res.width/res.height//获取原图比例

        that.setData({//构造画板宽高

          canWidth:500,

          canHeight:500/scale

})

//画出压缩图片

        ctx.drawImage(that.data.files, 0, 0, that.data.canWidth, that.data.canHeight);

        ctx.draw();

        //等待压缩图片生成

        var st =setTimeout(function(){

that.prodImageOpt();

          clearTimeout(st);

        },3000);

      }else{

//上传图片

        that.uploadFileOpt(that.data.files);

      }

}

})

},

prodImageOpt:function(){// 获取压缩图片路径

  var that =this;

  wx.canvasToTempFilePath({

canvasId:'attendCanvasId',

    success:function success(res) {

// 上传图片

      that.uploadFileOpt(res.tempFilePath);

    },

  });

},

uploadFileOpt:function(path){//上传图片

  let that=this;

  wx.uploadFile({

url:'/api/uploadPath', //后台上传api路径

    filePath: path,

    name:'file',

    success:function(res){

console.log(res);//因uploadFile无法在network中捕获故需打印返回内容

      //to do

    },

    fail:e=>{

//to do

    }

})

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问题: 图片上传后保存的图片跟原图不一致,还要待研究 //选择图片 chooseImg(e) { let t...
    wangwing阅读 5,527评论 0 0
  • 微信小程序图片压缩有三种方法,一种是使用官方提供的接口 wx.compressImage(Object objec...
    Dingry977阅读 56,175评论 4 18
  • 小程序压缩图片,已验证OK! 一、wx.compressImage() 官方提供的图片压缩方法,亲测iOS有效,A...
    zdh229阅读 12,776评论 0 3
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 7,916评论 0 3
  • 偶然一次在网上看到,一个外国摄影师用手机拍摄蚂蚁的照片,当时就兴奋不已,决定动手试试,效果出奇的好。一起看看吧! ...
    travelingl_b954阅读 3,352评论 2 4

友情链接更多精彩内容