微信小程序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)
	        }
	      })
	    })
	  }
	})
  }
});

本人开发的一个网站:编程之道,欢迎来踩!!!

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