微信小程序canvas中使用canvasToTempFilePath導出圖片尺寸與實際不符

需求

我想要將已有的圖片(可以通過拍照、選擇圖庫獲得)縮放爲指定大小,目標機器:華爲Meta9

問題描述

通過canvas可以寫入指定大小的圖片(微信小程序canvas官方文檔

  • wxml
<canvas style="width: {{canvasWidth}}px; height: {{canvasHeight}}px;" canvas-id="secondCanvas"></canvas>
  • js
wx.getImageInfo({
  src: imagePath,
  success: function (res) {

    // 生成指定寬度的圖片
    var canvasWidth = 576;
    var canvasHeight = canvasWidth / res.width * res.height;
    that.setData({
      canvasWidth: canvasWidth,
      canvasHeight: canvasHeight
    })
    var ctx = wx.createCanvasContext('secondCanvas');
    ctx.drawImage(imagePath, 0, 0, canvasWidth, canvasHeight);
    ctx.draw(true, function () {
      //保存臨時文件
      wx.canvasToTempFilePath({
        canvasId: 'secondCanvas',
        fileType: 'jpg',
        success: function (res) {
          console.log(res.tempFilePath)
          wx.getImageInfo({
            src: res.tempFilePath,
            success: function (res) {
                console.log(res)
                // 問題:這裏得到的圖片像素大小預期的大小不一致
            }
          });
         
        },
        fail: function (error) {
          console.log(error)
        }
      })
    })
  }
})

問題在於縮放後的圖片大小不是跟預期的一樣,預期是圖像寬度是576,高度按原圖片寬高比進行設置,結果得到的結果是:寬度:1728,高度:2000多

解決方案

canvas寫入的時候是按照當前設備像素比(pixelRatio)進行設置的

像素比pixelRatio=物理像素/設備獨立像素(dips)

我這臺機器的設備像素比=3,分辨率是:1920*1080
以x軸爲例,這裏的物理像素=1920,得出設備獨立像素=1920/3=640,而canvas這裏設置的大小是設備獨立像素,所以576的物理像素對應到設備獨立像素就是=576/3=192
微信小程序提供了wx.getSystemInfo獲取設備信息,其中pixelRatio就是設備像素比

最終代碼

wx.getSystemInfo({
  success: function (data) {
    var pixelRatio = data.pixelRatio;
		
	wx.getImageInfo({
	  src: imagePath,
	  success: function (res) {
	
	    // 生成指定寬度的圖片  這裏除於設備像素比
	    var canvasWidth = 576 / pixelRatio ;
	    var canvasHeight = canvasWidth / res.width * res.height;
	    that.setData({
	      canvasWidth: canvasWidth,
	      canvasHeight: canvasHeight
	    })
	    var ctx = wx.createCanvasContext('secondCanvas');
	    ctx.drawImage(imagePath, 0, 0, canvasWidth, canvasHeight);
	    ctx.draw(true, function () {
	      //保存臨時文件
	      wx.canvasToTempFilePath({
	        canvasId: 'secondCanvas',
	        fileType: 'jpg',
	        success: function (res) {
	          console.log(res.tempFilePath)
	          wx.getImageInfo({
	            src: res.tempFilePath,
	            success: function (res) {
	                console.log(res)
	            }
	          });
	         
	        },
	        fail: function (error) {
	          console.log(error)
	        }
	      })
	    })
	  }
	})
  }
});

本人開發的一個網站:編程之道,歡迎來踩!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章