-
Notifications
You must be signed in to change notification settings - Fork 198
/
sharp.js
executable file
·89 lines (83 loc) · 2.23 KB
/
sharp.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env node
/**
*@flow
*@format
*/
const fs = require("fs");
const path = require("path");
const sharp = require("sharp");
const formats = {
card: {
directory: path.join(__dirname, "assets", "images", "card"),
transformer: input =>
sharp(input)
.jpeg()
.resize(null, 220)
},
medium: {
directory: path.join(__dirname, "assets", "images", "medium"),
transformer: input =>
sharp(input)
.jpeg()
.resize(900)
},
small: {
directory: path.join(__dirname, "assets", "images", "small"),
transformer: input =>
sharp(input)
.jpeg()
.resize(500)
}
};
function loadAllLargeImages() {
const sourceDir = path.join(__dirname, "assets", "images", "large");
const sourceFiles = fs
.readdirSync(sourceDir)
.filter(
filename =>
filename.endsWith(".gif") ||
filename.endsWith(".jpg") ||
filename.endsWith(".jpeg") ||
filename.endsWith(".png") ||
filename.endsWith(".tiff") ||
filename.endsWith(".webp")
);
return sourceFiles.map(sourceFile => path.join(sourceDir, sourceFile));
}
function processImages(sourceFiles) {
let p = Promise.resolve();
for (let i = 0; i < sourceFiles.length; i++) {
const inputFile = sourceFiles[i];
const promises = [];
p = p.then(() => {
for (const formatName in formats) {
const format = formats[formatName];
const sourceFile = path.basename(inputFile);
const outputFile = path.join(format.directory, sourceFile);
console.log("generating", outputFile);
const processor = format.transformer(inputFile).toFile(outputFile);
promises.push(processor);
}
return Promise.all(promises);
});
}
}
function streamToPromise(filename, stream) {
return new Promise((resolve, reject) => {
stream.on("finish", () => {
console.log("finishing", filename);
resolve();
});
stream.on("error", error => {
console.log(filename, "failed!");
console.log(error);
reject();
});
});
}
if (process.argv.length > 2) {
const images = process.argv.slice(2);
processImages(images.map(image => path.join(__dirname, image)));
} else {
processImages(loadAllLargeImages());
}