-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (46 loc) · 1.61 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
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');
// Get command line arguments
const [,, inputPath, outputWidth, outputHeight, outputFolder] = process.argv;
// Check if input path exists and is a directory
if (!fs.existsSync(inputPath) || !fs.lstatSync(inputPath).isDirectory()) {
console.error(`Error: ${inputPath} is not a valid directory`);
process.exit(1);
}
// Ensure output directory exists
if (!fs.existsSync(outputFolder)) {
fs.mkdirSync(outputFolder);
}
// Loop through all files in input directory
fs.readdirSync(inputPath).forEach(file => {
const filePath = path.join(inputPath, file);
// Skip if not an image file
if (!/\.(jpe?g|png|gif)$/i.test(file)) {
console.log(`Skipping ${file} (not an image)`);
return;
}
// Check if the filename contains "@2x"
const isRetina = file.includes('@2x');
// Calculate the output dimensions
const width = parseInt(outputWidth) * (isRetina ? 2 : 1);
const height = parseInt(outputHeight) * (isRetina ? 2 : 1);
// Read image dimensions
sharp(filePath).metadata().then(metadata => {
// Skip if image already has desired dimensions
if (metadata.width === width && metadata.height === height) {
console.log(`Skipping ${file} (already resized)`);
return;
}
// Resize image
sharp(filePath)
.resize(width, height)
.toFile(path.join(outputFolder, file), (err, info) => {
if (err) {
console.error(`Error resizing ${file}: ${err.message}`);
} else {
console.log(`Resized ${file} to ${info.width}x${info.height}`);
}
});
});
});