forked from apachecn/doctool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
img-better.js
54 lines (42 loc) · 1.14 KB
/
img-better.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
/*
apt install imagemagick
apt install pngquant
*/
var chp = require('child_process')
var fs = require('fs')
var path = require('path')
var os = require('os')
function betterImg(img, tmpDir) {
tmpDir = tmpDir || os.tmpdir()
var fname = new Date().getTime().toString() + '.png'
fname = path.join(tmpDir, fname)
fs.writeFileSync(fname, img)
chp.spawnSync('convert', [fname + '[0]', fname])
chp.spawnSync('pngquant', ['8', fname, '-o', fname, '-f'])
img = fs.readFileSync(fname)
safeUnlink(fname)
return img
}
module.exports = betterImg
function safeUnlink(f){
try {fs.unlinkSync(f)}
catch(ex) {}
}
function main() {
var dir = process.argv[2]
var qualify = process.argv[3] || '8'
var pics = fs.readdirSync(dir).filter(
x => x.endsWith('.jpg') ||
x.endsWith('.png') ||
x.endsWith('.gif') ||
x.endsWith('.jpeg')
)
for(var f of pics){
f = path.join(dir, f)
console.log(f)
var img = fs.readFileSync(f)
img = betterImg(img)
fs.writeFileSync(f, img)
}
}
if(module == require.main) main()