核心调用代码如下:
/**
* @see http://www.html5plus.org/doc/zh_cn/zip.html#plus.zip.compressImage
* @param args
*/
static compressImage(args: {
imgPath: string, // absolute path or relative path
targetPath: string, // absolute path or relative path
fileSize: number,
retryCount?: number
}): Promise<string> {
console.log('compress file args:', args)
let compressCoefficient: number // 压缩系数
if (args.fileSize <= 1024 * 2000) compressCoefficient = 0.5
else compressCoefficient = (1024 * 1000) / args.fileSize
compressCoefficient = Math.round(compressCoefficient * 100)
console.log('compressCoefficient', compressCoefficient)
return new Promise((resolve,reject) => {
plus.zip.compressImage({
src: args.imgPath,
dst: args.targetPath,
overwrite: true,
quality: compressCoefficient,
},
(event: any) => {
const target = event.target // 压缩转换后的图片url路径,以"file://"开头
const size = event.size
console.log('压缩后文件的大小:', size)
if (!args.retryCount) args.retryCount = 0
// 三次没有压缩到想要的大小,放弃
if (args.retryCount < 3 && size > 1024 * 1000) {
args.retryCount ++
return resolve(this.compressImage({
imgPath: target, targetPath: args.targetPath,
fileSize: size, retryCount: args.retryCount
}))
}
resolve(target)
},
(e: any) => {
console.error(e)
reject(new CompressImageFailed())
}
)
})
}
0 个回复