image compression

This commit is contained in:
polv committed 2026-07-13 20:12:51 +07:00
1 parent e76a45f1d6
commit 8e6c5e2bda
2 files changed
+23 -1

No files matched your search

+3
View File
@@ -13,9 +13,12 @@ const WEBP_QUALITY = 75; // tweak 60-85 if you want smaller/larger
async function walk(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true });
console.log(dir, entries.filter((e) => !e.isDirectory()).length);
const files = [];
for (const e of entries) {
const p = path.join(dir, e.name);
if (p === OUT_DIR) continue;
if (e.isDirectory()) files.push(...(await walk(p)));
else files.push(p);
}
+20 -1
View File
@@ -3,12 +3,19 @@ import { WebSocketServer } from "ws";
import { readFileSync, mkdirSync, writeFileSync } from "fs";
import { join as joinPath } from "path";
import matter from "gray-matter";
import sharp from "sharp";
import { renderFile } from "./group-similar.js";
const MD_ROOT_DIR = "docs";
const IMG_ROOT_DIR = "docs/public/images";
const MAX_W = 800;
const MAX_H = 600;
const FORMAT = "webp";
const WEBP_QUALITY = 75; // tweak 60-85 if you want smaller/larger
const PORT = 8080;
const wss = new WebSocketServer({ port: PORT });
@@ -21,7 +28,19 @@ wss.on("connection", (ws) => {
ws.on("message", (message, isBinary) => {
if (message instanceof Buffer && isBinary) {
writeFileSync(joinPath(IMG_ROOT_DIR, filename), message);
sharp(message)
.rotate() // respects EXIF orientation
.resize({
width: MAX_W,
height: MAX_H,
fit: "inside", // preserve aspect, fit within box
withoutEnlargement: true, // don't upscale small images
})
.toFormat(FORMAT, {
quality: WEBP_QUALITY,
effort: 4,
})
.toFile(joinPath(IMG_ROOT_DIR, filename));
return;
}