-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresizeImages.js
More file actions
60 lines (50 loc) · 1.67 KB
/
resizeImages.js
File metadata and controls
60 lines (50 loc) · 1.67 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
import fs from "node:fs";
import path from "node:path";
import sharp from "sharp";
import process from "node:process";
const publicDir = path.resolve("public");
const outputBaseDir = path.resolve("public/optimized");
const maxWidth = 1280; // Max width of resized images
const isDirectory = (source) => {
return fs.lstatSync(source).isDirectory();
};
const projectFolders = fs
.readdirSync(publicDir)
.map((name) => path.join(publicDir, name))
.filter(isDirectory);
for (const projectFolder of projectFolders) {
const projectId = path.basename(projectFolder);
const outputProjectFolder = path.join(outputBaseDir, projectId);
if (!fs.existsSync(outputProjectFolder)) {
fs.mkdirSync(outputProjectFolder, { recursive: true });
}
const files = fs.readdirSync(projectFolder);
files.forEach((file) => {
const inputPath = path.join(projectFolder, file);
const ext = path.extname(file).toLowerCase();
if ([".jpg", ".jpeg", ".png", ".webp", ".tiff"].includes(ext)) {
const outputPath = path.join(
outputProjectFolder,
path.parse(file).name + ".webp"
);
sharp(inputPath)
.resize({ width: maxWidth })
.webp({ quality: 75 })
.toFile(outputPath)
.then(() => {
if (
typeof process.stdout.clearLine === "function" &&
typeof process.stdout.write === "function"
) {
process.stdout.clearLine();
process.stdout.write(
`\r✅ Resized and optimized ${projectId}/${file}`
);
}
})
.catch((err) => {
console.error(`❌ Error processing ${projectId}/${file}:`, err);
});
}
});
}