- 使用image-conversion实现图片压缩到指定大小
// 导入
import * as imageConversion from 'image-conversion'
/**
* 压缩小图到100kb
*/
compressImg(file) {
console.log('file: ', file)
return new Promise((resolve, reject) => {
if (file.size / 1024 <= 100) {
resolve(file)
} else {
try {
imageConversion.compressAccurately(file, { size: 100, width: 500 }).then(result => {
result = new File([result], file.name, { type: file.type, lastModified: Date.now() }) // blob转file
resolve(result)
})
} catch (error) {
console.log('compressImg error', error)
resolve(file)
}
}
})
}
- 这里的指定大小,只会压缩到指定大小左右,不会非常精准,width需要根据size调整