-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert_to_3by2.js
59 lines (52 loc) · 2.21 KB
/
convert_to_3by2.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
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');
function convertTo3_2(inputDir, outputDir) {
// Ensure output directory exists
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Read all files in the input directory
fs.readdir(inputDir, (err, files) => {
if (err) {
console.error(`Error reading directory: ${err}`);
return;
}
files.forEach(file => {
if (file.toLowerCase().endsWith('.jpg') || file.toLowerCase().endsWith('.jpeg')) {
const inputPath = path.join(inputDir, file);
const outputPath = path.join(outputDir, file);
// Open the image
sharp(inputPath)
.metadata()
.then(metadata => {
const { width, height } = metadata;
const aspectRatio = 3/2;
// Determine new dimensions
let newWidth, newHeight;
if (width / height > aspectRatio) {
newHeight = height;
newWidth = Math.round(newHeight * aspectRatio);
} else {
newWidth = width;
newHeight = Math.round(newWidth / aspectRatio);
}
// Resize and add black background
return sharp(inputPath)
.resize(newWidth, newHeight, {
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 1 }
})
.toFile(outputPath)
.catch(err => console.error(`Error processing file ${file}:`, err));
})
.then(() => console.log(`Converted ${file}`))
.catch(err => console.error(`Error in metadata step for ${file}:`, err));
}
});
});
}
// Usage
const inputDir = './tranchart_source_images/';
const outputDir = './tranchart_output_images/';
convertTo3_2(inputDir, outputDir);