小程序圖片壓縮

小程序圖片壓縮

?壓縮圖片原地址https://my.oschina.net/u/3362856/blog/1162498

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

? var that = this;

? wx.chooseImage({

? ? count:1,//最多可以選擇的圖片張數(shù),默認(rèn)9

? ? sizeType: [ 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有

? ? sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機(jī),默認(rèn)二者都有

? ? success: function (res) {

? ? ? // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的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({//構(gòu)造畫板寬高

? ? ? ? ? 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中捕獲故需打印返回內(nèi)容

? ? ? //to do

? ? },

? ? fail:e=>{

//to do

? ? }

})

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 問題: 圖片上傳后保存的圖片跟原圖不一致,還要待研究 //選擇圖片 chooseImg(e) { let t...
    wangwing閱讀 1,666評論 0 0
  • 微信小程序圖片壓縮有三種方法,一種是使用官方提供的接口 wx.compressImage(Object objec...
    Dingry977閱讀 56,303評論 4 18
  • 小程序壓縮圖片,已驗證OK! 一、wx.compressImage() 官方提供的圖片壓縮方法,親測iOS有效,A...
    zdh229閱讀 8,871評論 0 3
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom閱讀 3,214評論 0 3
  • 偶然一次在網(wǎng)上看到,一個外國攝影師用手機(jī)拍攝螞蟻的照片,當(dāng)時就興奮不已,決定動手試試,效果出奇的好。一起看看吧! ...
    travelingl_b954閱讀 526評論 2 4

友情鏈接更多精彩內(nèi)容