<canvas id="imageCanvas" style=" position: absolute; left: -999px; top: -999px; z-index: -1;" type="2d" />
zipImage(file) {
return new Promise((resolve, reject) = > {
wx.createSelectorQuery().select('#imageCanvas')
.fields({
node: true,
size: true
}).exec((res) = > {
const canvas = res[0].node
const context = canvas.getContext('2d')
const image = canvas.createImage()
image.src = file.url
image.onload = () = > {
let originWidth = image.width
let originHeight = image.height
console.log('原图图片宽高大小', originWidth, originHeight)
let maxWidth = 864, maxHeight = 648
let targetWidth = originWidth
let 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.width = targetWidth
canvas.height = targetHeight
setTimeout(() = > {
console.log('目标图片的宽高大小', targetWidth, targetHeight)
context.fillRect(0, 0, targetWidth, targetHeight)
context.drawImage(image, 0, 0, targetWidth, targetHeight)
wx.canvasToTempFilePath({
canvas, quality: 0.5,
fileType: 'jpg',
width: targetWidth / 2,
heght: targetHeight / 2,
destWidth: (targetWidth / 2) * wx.getWindowInfo().pixelRatio,
destHeight: (targetHeight / 2) * wx.getWindowInfo().pixelRatio,
success: (res) = > {
resolve(res.tempFilePath)
},
fail: (res) = > {
reject()
}
})
}, 500)
}
})
})
}
let tempFilePath = null
if (item.size > 1024 * 1024) {
tempFilePath = await this.zipImage(item).catch (err = > {
console.log('文件压缩失败')
})
}
const result = await upload(tempFilePath || item.url).catch ((err) = > {
console.log(err || '文件上传失败')
})
一些注意事项
- Canvas 生成的图片显示不全的话 请设置 canvas.width = targetWidth 和 canvas.height = targetHeight 以及 wx.canvasToTempFilePath 的 width、heght、destWidth、destHeight 参数。
- Canvas 显示正常但是导出的图片不正常的话 适当调节 wx.canvasToTempFilePath 外的 setTimeout 的时间。