-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompress.js
More file actions
34 lines (26 loc) · 1.1 KB
/
Copy pathcompress.js
File metadata and controls
34 lines (26 loc) · 1.1 KB
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
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const publicDir = path.join(__dirname, 'public');
async function compressImages() {
const files = fs.readdirSync(publicDir);
const pngFiles = files.filter(f => f.endsWith('.png'));
console.log(`Found ${pngFiles.length} PNG files to compress`);
for (const file of pngFiles) {
const inputPath = path.join(publicDir, file);
const outputPath = path.join(publicDir, file.replace('.png', '.webp'));
try {
const stats = fs.statSync(inputPath);
await sharp(inputPath)
.webp({ quality: 80 })
.toFile(outputPath);
const newStats = fs.statSync(outputPath);
const savings = ((1 - newStats.size / stats.size) * 100).toFixed(1);
console.log(`✓ ${file} → ${file.replace('.png', '.webp')} (${(stats.size/1024).toFixed(0)}KB → ${(newStats.size/1024).toFixed(0)}KB, -${savings}%)`);
} catch (err) {
console.error(`✗ Failed: ${file}`, err.message);
}
}
console.log('\nDone! You can now delete the original .png files.');
}
compressImages();