安装sharp
目前选择使用sharp 0.31.2版本
npm i sharp@0.31.2
并且在.npmrc里面配置镜像源
sharp_dist_base_url=https://npmmirror.com/mirrors/sharp-libvips/v8.13.3/
sharp_binary_host=https://npmmirror.com/mirrors/sharp
sharp_libvips_binary_host=https://npmmirror.com/mirrors/sharp-libvips
因为sharp有额外的依赖项。
官方文档
并没有在npm里列出,需要访问github,sharp文档
封装promise
export function compressPicture(filePath: string): Promise<Buffer> {return new Promise((resolve, reject)=>{sharp(filePath).rotate().resize(500).toBuffer().then( (data: any) => {resolve(data)}).catch( (err: any) => {reject(err)});})
}
图片压缩的大小可以自己选择。
接口处理
if (isPicture(filename)) {const result = await compressPicture(filePath)res.attachment(filename);return res.send(result)}return res.download(filePath)```
因为sharp返回的是buffer,要给前端文件可以用这个方式,express框架的写法。