Commit 85ea5a6d by wangzhihui

压缩上传图片功能

1 parent bd83eb48
...@@ -189,49 +189,193 @@ Page({ ...@@ -189,49 +189,193 @@ Page({
}) })
this.check() this.check()
}, },
async upload(e) { // async upload(e) {
const { // const {
item: { // item: {
key, // key,
} // }
} = e.currentTarget.dataset // } = e.currentTarget.dataset
console.log(e) // console.log(e)
const { // const {
tempFiles // tempFiles
} = await wx.chooseMedia({ // } = await wx.chooseMedia({
count: 1, // count: 1,
mediaType: ['image'] // mediaType: ['image'],
}), // sizeType:['compressed']
// }),
[file] = tempFiles, // [file] = tempFiles,
_this = this // _this = this
wx.p.wxApi.showLoading('上传中...') // wx.p.wxApi.showLoading('上传中...')
console.log(tempFiles, 'tempFiles') // console.log(tempFiles, 'tempFiles')
let fileUrl = file.tempFilePath // let fileUrl = file.tempFilePath
let imgType = fileUrl.split('.')[1] // let imgType = fileUrl.split('.')[1]
let type = imgType == 'unknown' ? 'jpg' : imgType // let type = imgType == 'unknown' ? 'jpg' : imgType
try { // try {
// wx.getFileSystemManager().readFile({
// filePath: fileUrl, //选择图片返回的相对路径
// encoding: 'base64', //编码格式
// success(_res) {
// wx.p.wxApi.showLoading('上传中...')
// wx.p.api.common.uploadImg({
// file: `${type}@${_res.data}`
// })
// .then(img => {
// wx.p.wxApi.hideLoading()
// _this.setData({
// [`formData.${key}`]: img
// })
// _this.check()
// })
// }
// })
// } catch (error) {
// wx.p.wxApi.showToast(String(JSON.stringify(error)))
// }
// },
async upload(e) {
const {
item: {
key,
}
} = e.currentTarget.dataset
console.log(e)
const {
tempFiles
} = await wx.chooseMedia({
count: 1,
mediaType: ['image'],
sizeType: ['compressed']
})
const [file] = tempFiles
const _this = this
wx.p.wxApi.showLoading('上传中...')
console.log(tempFiles, 'tempFiles')
let fileUrl = file.tempFilePath
let imgType = fileUrl.split('.')[1]
let type = imgType == 'unknown' ? 'jpg' : imgType
try {
// 读取图片文件并检查大小
const fileInfo = wx.getFileSystemManager().statSync(fileUrl)
const fileSize = fileInfo.size // 文件大小(字节)
const maxSize = 300 * 1024 // 300KB
// 如果文件大于300KB,需要进一步压缩
if (fileSize > maxSize) {
// 使用canvas压缩图片
const compressedBase64 = await this.compressImage(fileUrl, maxSize)
console.log(compressedBase64)
wx.p.wxApi.showLoading('上传中...')
wx.p.api.common.uploadImg({
file: `${type}@${compressedBase64}`
}).then(img => {
wx.p.wxApi.hideLoading()
_this.setData({
[`formData.${key}`]: img
})
_this.check()
})
} else {
// 文件小于300KB,直接上传
wx.getFileSystemManager().readFile({ wx.getFileSystemManager().readFile({
filePath: fileUrl, //选择图片返回的相对路径 filePath: fileUrl,
encoding: 'base64', //编码格式 encoding: 'base64',
success(_res) { success(_res) {
wx.p.wxApi.showLoading('上传中...') wx.p.wxApi.showLoading('上传中...')
wx.p.api.common.uploadImg({ wx.p.api.common.uploadImg({
file: `${type}@${_res.data}` file: `${type}@${_res.data}`
}) }).then(img => {
.then(img => { wx.p.wxApi.hideLoading()
wx.p.wxApi.hideLoading() _this.setData({
_this.setData({ [`formData.${key}`]: img
[`formData.${key}`]: img
})
_this.check()
}) })
_this.check()
})
} }
}) })
} catch (error) {
wx.p.wxApi.showToast(String(JSON.stringify(error)))
} }
}, } catch (error) {
wx.p.wxApi.hideLoading()
wx.p.wxApi.showToast('图片处理失败')
console.error(error)
}
},
// 压缩图片的方法
compressImage(filePath, maxSize) {
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: filePath,
success(res) {
// 创建画布
const canvas = wx.createOffscreenCanvas({
type: '2d',
width: res.width,
height: res.height
});
// 创建图片对象
const img = canvas.createImage();
img.onload = () => {
// 计算压缩比例
let ratio = 1;
if (res.width > 1000 || res.height > 1000) {
ratio = Math.min(1000 / res.width, 1000 / res.height);
}
const canvasWidth = res.width * ratio;
const canvasHeight = res.height * ratio;
// 调整画布大小
canvas.width = canvasWidth;
canvas.height = canvasHeight;
const ctx = canvas.getContext('2d');
// 绘制图片
ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
// 逐步降低质量直到满足大小要求
let quality = 0.9;
const tryCompress = () => {
try {
const dataURL = canvas.toDataURL('image/jpeg', quality);
const base64Data = dataURL.replace(/^data:image\/\w+;base64,/, '');
const byteLength = base64Data.replace(/[^A-Za-z0-9+/]/g, '').length * 0.75;
if (byteLength <= maxSize || quality <= 0.1) {
// 满足大小要求或质量已降到最低
resolve(base64Data);
} else {
// 继续降低质量
quality -= 0.1;
tryCompress();
}
} catch (err) {
reject(err);
}
};
tryCompress();
};
img.onerror = (err) => {
reject(err);
};
// 设置图片源
img.src = filePath;
},
fail(err) {
reject(err);
}
});
});
},
async getBankList() { async getBankList() {
const { const {
bankList bankList
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!