mahee-auffret/ssg_hooks/resizeImages.js

35 lines
1.0 KiB
JavaScript
Raw Normal View History

2024-04-15 23:24:48 +02:00
import fs from 'fs';
import sharp from 'sharp';
export async function resizeImages(sizes) {
const sourceFolder = './public/api/assets';
const outputFolder = './.output/public';
for (const size of sizes) {
const key = Object.keys(size)[0];
const sizeFolder = `${outputFolder}/${key}`;
if (!fs.existsSync(sizeFolder)) {
fs.mkdirSync(sizeFolder, { recursive: true });
}
}
const files = fs.readdirSync(sourceFolder);
for (const file of files) {
const filePath = `${sourceFolder}/${file}`;
const image = sharp(filePath);
for (const size of sizes) {
const key = Object.keys(size)[0];
const sizeFolder = `${outputFolder}/${key}`;
const width = parseInt(size[key]);
await image.clone().resize({ width }).toFile(`${sizeFolder}/${file}`);
}
}
// fs.rmSync('./.output/public/api/assets', { recursive: true, force: true });
console.log('Images resized and saved successfully.');
}