vscode-图片压缩
vscode-图片压缩, 上传 md 笔记中使用到的图片 到图床前, 进行一次 ‘瘦身’
前篇
- 官方
- https://github.com/imagemin/imagemin
- 从图片优化说起 - https://cjting.me/2019/07/29/image-optimization/
- 图像优化如何使我的网站页面重量减少62% - https://segmentfault.com/a/1190000018392559
因为我是用 vscode 写了个插件监听某个文件夹, 监听到到有图片新增, 就自动上传到 七牛云 图传, 所以就把这个 图片瘦身 功能集成 vscode 中.
压缩为 webp 格式
安装插件
1
2npm install --save imagemin
npm install --save imagemin-webp压缩图片
1
2
3
4
5
6
7
8
9
10
11
12
13
14const images = ['F:/a_desktop/20200330_143904.png', 'F:/a_desktop/20200330_143902.png'] // 一定要是 /, 因为这里使用的是 glob 匹配模式, 如: 'images/*.{jpg,png}'
const output = 'F:/a_desktop/output'
const quality = 80
const webps = await imagemin(images, {
destination: output,
plugins: [
imageminWebp({
quality: quality,
}),
],
});
// console.log("--- webps: ", typeof(webps));
// [{data: <Buffer 89 50 4e …>, destinationPath: 'build/images/foo.jpg'}, …]
const resArr = Object.keys(webps).map(key => webps[key].destinationPath);
vscode 中的完整源码
PicTool.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25const imagemin = require('imagemin');
const imageminWebp = require('imagemin-webp');
class PicTool {
// images 是一个 glob 数组, 如: ['images/*.{jpg}']
public static imageminToWebp(images: string[], output: string, quality: number) {
return new Promise<string[]>(async (resolve, reject) => {
const webps = await imagemin(images, {
destination: output,
plugins: [
imageminWebp({
quality: quality,
}),
],
});
// console.log("--- webps: ", typeof(webps));
// [{data: <Buffer 89 50 4e …>, destinationPath: 'build/images/foo.jpg'}, …]
const resArr = Object.keys(webps).map(key => webps[key].destinationPath);
resolve(resArr)
});
}
}
export default PicTool;使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import PicTool from './PicTool';
// 是否自动上传, vscode 配置参数
export interface IQiniuAuto {
isCompress: boolean
isAutoUpload: boolean // 是否监听文件
quality: number // 压缩质量
isUpload: boolean // 用于是否上传
}
// 压缩图片
let autoCfg = this.cfg.get<IQiniuAuto>(E_CONFIG.autoUploadQiniu);
if (autoCfg.isCompress) {
const tempDir = path.join(vscode.workspace.rootPath, 'compressTempSave');
const picArr = await PicTool.imageminToWebp(filePathArr, tempDir, autoCfg.quality) // 关键代码
for (const srcFile of filePathArr) { // 删除 原图
Utils.delFileSync(srcFile);
}
filePathArr = picArr // 生成压缩图路径数组
}