-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (86 loc) · 2.54 KB
/
index.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
90
91
92
93
94
95
96
97
import sharp from "sharp";
import { existsSync, mkdirSync } from "fs";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
// Command line arguments
const argv = yargs(hideBin(process.argv))
.option("source", {
alias: "s",
description: "The image source",
type: "string",
demandOption: true,
})
.option("max", {
alias: "m",
description: "The optimized max image width",
type: "number",
default: 5120,
})
.option("output", {
alias: "o",
description: "The output directory",
type: "string",
default: "./output",
})
.help()
.alias("help", "h").argv;
// Configurations
const imageSizes = [
320, 440, 512, 768, 1024, 1280, 1536, 1792, 2048, 2560, 3072, 3584, 5120,
];
const sourceDir = "./images";
const outputDir = argv.output;
const maxSize = argv.max;
const sourceImages = argv.source.split(",");
const sizes = imageSizes.filter((size) => size <= maxSize);
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
// Process image metadata
function processImage(imagePath) {
const formatRegex = /\.(jpg|jpeg|png|gif)$/i;
const match = imagePath.match(formatRegex);
if (match) {
const [fullMatch, format] = match;
const imageName = imagePath.replace(fullMatch, "");
return { name: imageName, format };
} else {
console.error(`✖ Unsupported image format for ${imagePath}`);
return null;
}
}
// Resize images to each specified size
async function resizeImage(size, imageData) {
const inputPath = `${sourceDir}/${imageData.name}.${imageData.format}`;
const outputPath = `${outputDir}/${imageData.name}-${size}.${imageData.format}`;
if (!existsSync(inputPath)) {
console.error(`✖ Source image ${inputPath} does not exist!`);
return;
}
try {
await sharp(inputPath)
.resize(size)
.toFormat(imageData.format, { quality: 80 })
.toFile(outputPath);
console.log(
`✓ ${imageData.name} resized to ${size} and saved to ${outputPath}`
);
} catch (error) {
console.error(
`✖ Error resizing ${imageData.name} to ${size}: ${error.message}`
);
}
}
// Main function to process and resize all images
(async function () {
const imagesData = sourceImages.map(processImage).filter(Boolean); // Filter out nulls
await Promise.all(
imagesData.map(async (imageData) => {
await Promise.all(sizes.map((size) => resizeImage(size, imageData)));
console.log(
`%c✓ ${imageData.name} optimized and resized to ${sizes.join(", ")}`,
"color: #FFD700"
);
})
);
})();