安装
npm install imagemin@7.0.1
npm install imagemin-gifsicle@7.0.0
安装时要注意下两者之间的版本。(imagemin的8.0.0版本是ES6模块化)
使用
const imagemin = require('imagemin')
const imageminGifsicle = require('imagemin-gifsicle')
// fileAbPath: 图片的路径数组 D:/image/a.gif
// outPath: 输出路径,输出文件名与原文件名一致
// colors: 压缩后图片的颜色值, 值越小图片大小就越小 2~256
async compressGifImg({ fileAbPath, outPath = 'D:/min', colors = 64 }) {
console.log('compressGifImg', fileAbPath, outPath, colors)
try {
const files = await imagemin([fileAbPath], {
destination: outPath,
glob: false,
plugins: [
imageminGifsicle({
optimizationLevel: 3,
colors
})
]
})
console.log('compress success')
return files
} catch (error) {
console.log(error)
}
}
如果想把某个目录下的gif全部压缩:glob传true,图片路径使用通配符
async compressGifImg({ fileAbPath: 'D:/image/*.gif', outPath = 'D:/min', colors = 64 }) {
console.log('compressGifImg', fileAbPath, outPath, colors)
try {
const files = await imagemin([fileAbPath], {
destination: outPath,
glob: true,
plugins: [
imageminGifsicle({
optimizationLevel: 3,
colors
})
]
})
console.log('compress success')
return files
} catch (error) {
console.log(error)
}
}