说明:上下两张图是分别用真机和开发者工具上传的同一张图片,上图是真机传的,下图是开发者工具。想问问大神们为什么会出现这种情况?
下面是上传图片后获取图片信息并在canvas上绘制新图片的代码,后面保存上传图片的代码就省略了
let uploadFile = '' // 最后处理完,图片上传的图片地址
let tempFilePath = res.tempFilePaths[0]
// 获得原始图片大小
wx.getImageInfo({
src: tempFilePath,
success(res) {
// console.log('获得原始图片大小',res.width)
// console.log(res.height)
var originWidth, originHeight
originHeight = res.height
originWidth = res.width
console.log("origin:" + originWidth)
// 压缩比例
// 最大尺寸限制
var maxWidth = 1420,
maxHeight = 800
// 目标尺寸
var targetWidth = originWidth,
targetHeight = originHeight
// 等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 要求宽度 * (原生图片比例) = 新图片尺寸
targetWidth = maxWidth
targetHeight = Math.round(maxWidth * (originHeight / originWidth))
} else {
targetHeight = maxHeight
targetWidth = Math.round(maxHeight * (originWidth / originHeight))
}
}
// 尝试压缩文件,创建canvas
console.log(targetWidth, targetHeight)
console.log(tempFilePath)
that.setData({
cw: targetWidth,
ch: targetHeight
})
var ctx = wx.createCanvasContext('firstCanvas', this)
ctx.clearRect(0, 0, targetWidth, targetHeight)
ctx.drawImage(tempFilePath, 0, 0, targetWidth, targetHeight)
ctx.draw(false, () => {
wx.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: (res) => {
不如贴些代码出来,这谁知道呢。。。
估计是canvas的高宽啥的没设置?
新接口 https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html