1.npm 安装?image-compressor.js
2.引入?import ImageCompressor from 'image-compressor.js'
3.使用
const compressImage = async (file: any) => {
var imageCompressor = new ImageCompressor()
return new Promise((resolve, reject) => {
imageCompressor
.compress(file, { quality: 0.8, maxHeight: 100, maxWidth: 100 })
.then((result) => {
resolve(result)
})
.catch((err) => {
reject(err)
})
})
}
// 这个方法是异步的,使用时记得
const afterRead = async (res: any) => {
let file = await compressImage(files)
}
const blobToBase64 = (blob: any) => {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => {
resolve(reader.result)
}
reader.onerror = reject
reader.readAsDataURL(blob)
})
}