有api是压缩质量的:
wx.compressImage({
src: originPath, // 图片路径
quality: 90, // 压缩质量
success: function (res) {
res.tempFilePath//结果路径
}
})
压缩尺寸没有api,需要自己实现。
可使用canvas绘制图片,然后保存。设置画布的大小,相当于控制了图片尺寸。
实现步骤:
1.在wxml上定义画布:(不支持动态创建canvas)
<!-- 通过css控制在界面上不可见。 -->
<canvas style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;position:fixed;left:100%;" id="picCanvas" type="2d"></canvas>
2.js代码:
//获取原图片信息
wx.getImageInfo({
src: path,
success: function (res) {
let canvasRatio = 1.1;
let picWidth = res.width //图片原始长宽
let picHeight = res.height
while (picWidth > 400 || picHeight > 400) { // 保证宽高在400以内
picWidth = Math.trunc(res.width / canvasRatio)
picHeight = Math.trunc(res.height / canvasRatio)
canvasRatio = canvasRatio + 0.1;
}
const query = wx.createSelectorQuery()
query.select('#picCanvas').fields({
node: true,
size: true
}).exec((res) => {
try {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
let dpr = wx.getSystemInfoSync().pixelRatio
//这里是设置css样式的宽高。
//属性宽高是css样式宽高的dpr倍,兼容不同机型,避免绘制的内容模糊。
that.setData({
canvasWidth: picWidth / dpr,
canvasHeight: picHeight / dpr
})
canvas.width = picWidth
canvas.height = picHeight
const img = canvas.createImage()
img.src = path
img.onload = () => {
ctx.drawImage(img, 0, 0, picWidth, picHeight); //先画出图片
//延迟600ms,避免部分机型未绘制出图片内容就执行保存操作,导致最终的图片是块白色画板。
setTimeout(() => {
wx.canvasToTempFilePath({
fileType: "jpg",
canvas: canvas,
destWidth: picWidth,
destHeight: picHeight,
success: function (res) {
var tempFilePath = res.tempFilePath//结果路径
}
}, that)
}, 600)
}
} catch (e) {
//异常后的操作
}
})
}
})
一些避免踩坑的关键点都在代码注释里。
此文完毕。