-
Notifications
You must be signed in to change notification settings - Fork 0
/
imgcompress.js
66 lines (60 loc) · 1.65 KB
/
imgcompress.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminPngquant = require('imagemin-pngquant');
const ImageminGm = require('imagemin-gm')
const imageminGm = new ImageminGm()
const fs = require('fs');
const path = require('path');
const argv = require('minimist')(process.argv.slice(2));
let inDir, outDir;
// set input and output folders
if (argv.in) {
inDir = argv.in;
} else {
inDir = '.';
}
if (argv.out) {
outDir = argv.out;
} else {
outDir = 'optimized';
}
// scale down & compress images
imagemin([`${inDir}/*.{jpg,png}`], outDir, {
plugins: [
imageminGm.resize({ width: 1920, height: 1000, gravity: 'Center' }),
imageminMozjpeg({quality: '60'}),
imageminPngquant({quality: '65-80'}),
]
}).then(files => {
console.log('Image Optimization Reults');
console.log('==============================');
logStats(files);
}, error => {
console.log(error);
});
function logStats(files) {
let totalSaved = 0;
files.forEach(function(obj) {
let stats = getStats(obj.path);
console.log(
Math.round((stats.oldSize - stats.newSize) / stats.oldSize * 100) + '%',
stats.file
);
totalSaved += stats.oldSize - stats.newSize;
});
console.log('======================\n', btokb(totalSaved) + ' Saved');
console.log('', 'Files written to ' + outDir);
}
function getStats(file) {
let fileName = path.parse(file).base;
let fileStats = fs.statSync(file);
let oldFileStats = fs.statSync(path.join(inDir, fileName));
return {
file: fileName,
oldSize: oldFileStats['size'],
newSize: fileStats['size']
};
}
function btokb(val) {
return (val / 1000).toFixed(1) + 'kb';
}