I made my own image minifier so you don't have to

Since I can’t seem to get Trimage working on my Linux machine any more, I decided to make my own command line tool.

imagemin.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 imageminGifsicle = require('imagemin-gifsicle');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminPngquant = require('imagemin-pngquant');
const imageminSVG = require('imagemin-svgo');
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';
}

console.log('Processing images...\n');

imagemin([`${inDir}/*.{jpg,png,gif,svg}`], outDir, {
plugins: [
imageminMozjpeg({quality: '80'}),
imageminPngquant({quality: '65-80'}),
imageminGifsicle(),
imageminSVG()
]
}).then(files => {
console.log('Image Optimization Reults');
console.log('==============================');
logStats(files);
});

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';
}

Ye olde dependencies. Add these globally if your script is flying solo.

1
yarn add imagemin imagemin-gifsicle imagemin-mozjpeg imagemin-pngquant imagemin-svgo minimist

Then in your .zshrc or .bashrc:

1
alias imagemin="node ~/scripts/imagemin.js"

To run it:

1
imagemin --in indirectory --out outdirectory

It’s simpler than it looks. Most of the code is for reporting. Out of the box imagemin doesn’t tell you anything beyond “done”. When this runs it reports the percentage saved for each file, then the total size savings in kilobytes. I want a pat on the head for making the web a better place, damnit.