nycki.net/tools/img-shrink.js

38 lines
1.2 KiB
JavaScript
Raw Normal View History

import fs from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';
const dirIn = 'tools/in';
const dirOut = 'tools/out';
const thresholdBytes = 2 * 1024 * 1024;
const quality = [100, 87, 75, 62, 50, 37, 25, 12];
2024-12-01 03:35:41 +00:00
async function main() {
for (const base of await fs.readdir(dirIn)) {
2024-12-01 03:35:41 +00:00
if (base === '.gitkeep') continue;
const fileIn = `${dirIn}/${base}`;
const { name } = path.parse(fileIn);
const { size } = await fs.stat(fileIn);
if (size <= thresholdBytes) {
const fileOut = `${dirOut}/${base}`;
console.log(`${fileIn} -> ${fileOut} (no changes)`);
fs.copyFile(fileIn, fileOut);
continue;
}
const fileOut = `${dirOut}/${name}.jpg`;
for (let i = 0; i < quality.length; i += 1) {
const newStats = await (sharp(fileIn)
.withMetadata()
.jpeg({ mozjpeg: true, quality: quality[i] })
.toFile(fileOut)
);
if (i == quality.length || newStats.size <= thresholdBytes) {
console.log(`${fileIn} -> ${fileOut} (quality: ${quality[i]})`);
break;
}
}
2024-12-01 03:35:41 +00:00
}
}
main();