图片压缩工具

使用 tinypng 来批量压缩图片

官网

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const fs = require('fs');
const path = require('path');
const tinify = require('tinify'); // 需要安装 tinify 模块

// 设置 tinify API key
// https://tinypng.com/developers
tinify.key = '你的KEY';

async function compressFiles(dir, blackDirs = []) {
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const file = files[i];
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);

if (stat.isDirectory()) {
if (blackDirs.indexOf(file) === -1) {
await compressFiles(filePath, blackDirs);
} else {
console.log(`Skip directory: ${filePath}`);
}
} else if (/\.(png|jpe?g)$/i.test(filePath)) {
console.log(`Compressing ${filePath}...`);
const source = tinify.fromFile(filePath);
await source.toFile(filePath);
}
}
}

function task(path) {
const inputDir = path.resolve(__dirname, path);

// 排除的文件夹名称,不用完整路径
const blackDirs = []
compressFiles(inputDir, blackDirs).then(() => {
console.log('All files compressed successfully!');
}).catch((err) => {
console.error('Error occurred while compressing files:', err);
});
}

// ====================
// 运行
const absolutePath = "目标目录完整路径(E:/images/xxx/)";
task(absolutePath);