forked from QuantStack/quantstack.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresize-images.mjs
More file actions
47 lines (44 loc) · 1.73 KB
/
resize-images.mjs
File metadata and controls
47 lines (44 loc) · 1.73 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
import sharp from 'sharp';
import fs from 'fs';
import path from 'path';
import sizeOf from 'image-size';
import { fileURLToPath } from 'url';
const containerHeight = 180;
const containerWidth = 273;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const fullSizeDir = path.join(__dirname, '../static', 'img', 'blogposts', 'full-size-images');
const reducedSizeDir = path.join(__dirname, '../static', 'img', 'blogposts', 'resized-images');
if (!fs.existsSync(reducedSizeDir)) {
fs.mkdirSync(reducedSizeDir, { recursive: true });
}
function calculateImageSize(fullSizePath) {
if (fs.existsSync(fullSizePath)) {
const width = sizeOf(fullSizePath).width;
const height = sizeOf(fullSizePath).height;
let targetWidth, targetHeight;
if (width * containerHeight > containerWidth * height) {
targetWidth = containerWidth * 2;
targetHeight = Math.round(targetWidth / width * height);
if (targetHeight > containerHeight) {
targetHeight = containerHeight;
targetWidth = Math.round(targetHeight * width / height);
}
}
else {
targetHeight = containerHeight;
targetWidth = Math.round(targetHeight * width / height);
}
return [targetWidth, targetHeight];
}
}
fs.readdirSync(fullSizeDir).forEach((file) => {
const fullSizePath = path.join(fullSizeDir, file);
const reducedSizePath = path.join(reducedSizeDir, file);
const [targetWidth, targetHeight] = calculateImageSize(fullSizePath);
if (/\.(png|jpg)$/i.test(file)) {
sharp(fullSizePath)
.resize(targetWidth, targetHeight)
.toFile(reducedSizePath)
}
})