-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.js
56 lines (51 loc) · 1.45 KB
/
convert.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
const gm = require('gm');
const ReadableStreamClone = require('readable-stream-clone');
const fs = require('fs');
readFiles().then(function(filenames) {
resizeImages(filenames);
})
function readFiles() {
const filenames = [];
return new Promise((resolve, reject) => {
fs.readdir('./in', (err, files) => {
files.forEach(filename => {
filenames.push(filename);
});
resolve(filenames);
});
});
}
async function resizeImages(filenames) {
for (let filename of filenames) {
console.log(`resizing image: ${filename}`);
const filestream = fs.createReadStream(`./in/${filename}`);
await resizeImage(filestream, 1000, filename);
}
}
// Maintains aspect ratio
function resizeImage(
filestream,
imageWidth,
filename
) {
return new Promise((resolve, reject) => {
const stream = new ReadableStreamClone(filestream);
gm.subClass({ imageMagick: true })(stream)
.background('white')
.flatten()
.fuzz('1%')
.resize(imageWidth)
.autoOrient()
.quality(80)
.setFormat('jpg')
.stream((err, stdout) => {
if (!err) {
const writeStream = fs.createWriteStream(`./out/${filename}`);
stdout.pipe(writeStream);
stdout.on('end', function() { resolve(); })
} else {
console.log(err);
}
});
});
}