试用场景:上传图片过大,需进行压缩处理。
涉及微信API
API | 说明 | 文档 |
---|---|---|
chooseImage | 选择图片 | https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html |
createCanvasContext | 创建canvas画布 | https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.createCanvasContext.html |
getImageInfo | 获取图片信息 | https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.getImageInfo.html |
CanvasContext.drawImage() | 绘制图像到画布 | https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.drawImage.html |
CanvasContext.draw() | 绘制是否跟着上次绘制,即是否清空画板 | https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.draw.html |
canvasToTempFilePath | 把当前画布导出指定大小的图片,即压缩图片 | https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasToTempFilePath.html |
wxml
<!--不显示画板且正常获取生成的压缩图片-->
<canvas
style=" {{canWidth}}px;height: {{canHeight}}px;visibility:hidden;z-index: -1px"
canvas-id="attendCanvasId"
class="pa tp-0 lf-0"/>
<view
bindtap='create'
style="background-color: {{themeColor}}"
class="dib pl-30 pr-30 ht-80 lh-80 bdr-100 white wi-100 tc fs-32">
上传图片
</view>
js
data: {
// 接收选中的图片列表
files: [],
// 接收压缩后的图片
compressFiles: [],
// 预设画布宽高
canvasWidth: 0,
canvasHeight: 0
},
// 选择图片
chooseImage: function () {
var that = this;
wx.chooseImage({
count: 6, // 设置允许选择的图片个数
sizeType: ['compressed'], // 压缩图
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
that.setData({
files: that.data.files.concat(res.tempFilePaths)
})
}
})
},
// 绘图
drawCanvas: function () {
this.setData({
compressFiles: []
}, () => {
const ctx = wx.createCanvasContext('attendCanvasId')
let that = this
for (let i in this.data.files) {
let item = this.data.files[i]
wx.getImageInfo({
src: item,
success: function (res) {
if (res.width > 275 || res.height > 172) { // 判断图片超过一定像素侯进行压缩
// 获取原图比例
let scale = res.width / res.height
that.setData({
canvasWidth: 275,
canvasHeight: 275 / scale
})
// 画出压缩图片
ctx.drawImage(that.data.files, 0, 0, that.data.canvasWidth, that.data.canvasHeight)
ctx.draw()
// 等待压缩图片生成
that.prodImageOpt()
}
}
})
}
})
},
// 压缩图片
prodImageOpt: function () {
let that = this
wx.canvasToTempFilePath({
canvasId: 'attendCanvasId', // 画布id
fileType: 'jpg', // 压缩图片的格式
quality: 1, // 压缩图片的质量,进‘jpg’格式可用
success: function (res) {
let arr = that.data.compressFiles
arr.push(res.tempFilePath)
that.setData({
compressFiles: arr
})
// 查看文件压缩后的信息
// wx.getImageInfo({
// src: res.tempFilePath,
// success: function (res) {
// console.log(res)
// }
// })
}
})
},
// 上传图片
create: function () {
let arr = this.drawCanvas() // 提交表单时绘制画布并进行压缩
setTimeout(() => {
// 获取压缩后的图片路径
console.log(this.data.compressFiles)
}, 300)
// 请求函数
...
...
...
}