-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimize-images
More file actions
executable file
·95 lines (93 loc) · 2.86 KB
/
Copy pathoptimize-images
File metadata and controls
executable file
·95 lines (93 loc) · 2.86 KB
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
90
91
92
93
94
95
#!/usr/bin/env node
const sharp = require("sharp");
const fs = require("fs");
const { optimize } = require("svgo");
function optimizeFolderImages({ sourceDir, size }) {
const destinationDir = `${sourceDir}/optimized`;
return new Promise((resolve, reject) => {
fs.readdir(sourceDir, { withFileTypes: true }, function (err, files = []) {
if (err) {
console.log("Unable to scan directory: " + err);
reject(err);
}
files.forEach((dirent) => {
if (dirent.isFile()) {
const file = dirent.name;
console.log("Optimizing image " + file);
let destinationFilename = file
.replace("[^a-zA-Z0-9]+", "-")
.replace(".jpeg", ".jpg")
.replace(".png", ".jpg");
if (file.endsWith(".svg")) {
try {
const data = fs.readFileSync(`${sourceDir}/${file}`, "utf8");
const result = optimize(data, {
path: `${destinationDir}/${destinationFilename}`,
});
fs.writeFileSync(
`${destinationDir}/${destinationFilename}`,
result.data
);
} catch (error) {
console.log(error);
}
} else {
let result = sharp(`${sourceDir}/${file}`)
.resize(size, undefined, {
withoutEnlargement: true,
})
.jpeg()
.flatten({ background: { r: 255, g: 255, b: 255 } });
result
.clone()
.toBuffer()
.then((data) => {
fs.writeFileSync(
`${destinationDir}/${destinationFilename}`,
data
);
})
.catch((err) => {
console.log(err);
});
result
.clone()
.avif({ quality: 65 })
.toBuffer()
.then((data) => {
fs.writeFileSync(
`${destinationDir}/${destinationFilename.replace(
".jpg",
".avif"
)}`,
data
);
})
.catch((err) => {
console.log(err);
});
}
}
});
resolve();
});
});
}
if (fs.existsSync("static/img/communities/optimized")) {
fs.rmSync("static/img/communities/optimized", { recursive: true });
}
if (fs.existsSync("static/img/sponsors/optimized")) {
fs.rmSync("static/img/sponsors/optimized", { recursive: true });
}
fs.mkdirSync("static/img/communities/optimized");
fs.mkdirSync("static/img/sponsors/optimized", { recursive: true });
Promise.all([
optimizeFolderImages({
sourceDir: "static/img/communities",
size: 240,
}),
optimizeFolderImages({
sourceDir: "static/img/sponsors",
size: 240,
}),
]);