// 图片压缩
compressImage (image = {}, options = {}) {
return new Promise((resolve, reject) => {
const { width = 0 } = image
const { compressAfterSizeFlag = false, scaleFlag = false, scaleTargetWidth = 768 } = options
// 超过100k压缩
const maxFileSizeLimit = 100 * 1024
if (image.size > maxFileSizeLimit) {
const fileSize = image.size / 1024
// 初始压缩率80
let quality = 80
if (fileSize > 200 && fileSize <= 500) {
// 200 以上,500k以内的图片,压缩70
quality = 60
} else if (fileSize > 500 && fileSize <= 1024) {
// 500 以上,1M以内的图片,压缩50
quality = 40
} else if (fileSize > 1024 && fileSize <= 2048) {
// 1M 以上,2M以内的图片,压缩30
quality = 30
} else if (fileSize > 2048 && fileSize <= 5012) {
// 2M 以上,5M以内的图片,压缩20
quality = 20
} else if (fileSize > 5012) {
// 5M以上的图片,压缩10
quality = 10
}
// 开始压缩
const option = {
src: image.filePath,
quality: quality,
success: res => {
image.compressPath = res.tempFilePath
if (compressAfterSizeFlag) {
// 获取压缩后的大小
uni.getFileSystemManager().readFile({
filePath: res.tempFilePath,
success: ({ data }) => {
image.compressSize = data.byteLength
resolve(image)
},
fail: _ => resolve(image)
})
} else {
resolve(image)
}
},
fail: _ => {
resolve(image)
}
}
// 缩放图片
if (scaleFlag && width > scaleTargetWidth) {
option.compressedWidth = scaleTargetWidth
}
uni.compressImage(option)
} else {
resolve(image)
}
})
},
// 四舍五入
toFixed (value = 0, decimal = 2) {
if (!value || isNaN(Number(value))) {
return value
}
let valueStr = String(value)
if (valueStr.length < 2 || valueStr.lastIndexOf('.') < 0) {
return value
}
const multiplier = Math.pow(10, decimal + 1)
const valueMultiplier = Math.trunc(value * multiplier)
const valueMultiplierStr = String(valueMultiplier)
return (Number(valueMultiplierStr.substring(0, valueMultiplierStr.length - 1))
- (Number(valueMultiplierStr.substring(valueMultiplierStr.length - 1)) >= 5 ? 1 : 0)) / Math.pow(10, decimal)
},