nycki.net/tools/img-shrink.js

49 lines
1.4 KiB
JavaScript
Raw Permalink 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;
2024-12-27 02:30:15 +00:00
const quality = [100, 99, 97, 95, 90, 80, 75, 70, 60, 50, 40];
2024-12-01 03:35:41 +00:00
2024-12-28 06:22:51 +00:00
async function makedir(dir) {
try {
await fs.stat(dir);
} catch (err) {
if (err.code !== 'ENOENT') throw err;
await fs.mkdir(dir);
}
}
2024-12-01 03:35:41 +00:00
async function main() {
2024-12-28 06:22:51 +00:00
await makedir(dirIn);
await makedir(dirOut);
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();