source: Klonkt/src/services/ImageWebpService.js@ d219d56

main
Last change on this file since d219d56 was 8f6225c, checked in by roboburr <roboburr@…>, 3 months ago

feat(images): new uploads automatically converted to WebP

Shared ImageWebpService.toWebp() converts uploaded images via cwebp (q82)
and removes the original; cwebp absent/error → original preserved (graceful).
Wired up in all upload routes: post images/cover, avatar, site photo, hub
hero, audio cover. GIF stays GIF, already-webp skipped.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 1.7 KB
Line 
1/**
2 * Zet een zojuist-geüploade afbeelding om naar WebP (kleiner, modern).
3 *
4 * Gebruikt het systeem-`cwebp` (libwebp). Aanwezig → converteer + verwijder het
5 * origineel, geef de nieuwe .webp-bestandsnaam terug. Niet aanwezig of fout →
6 * geef de originele bestandsnaam terug (graceful fallback, niks breekt).
7 *
8 * GIF blijft GIF (cwebp maakt geen geanimeerde webp van een gif); reeds-webp
9 * wordt overgeslagen.
10 */
11import { execFileSync } from 'child_process';
12import fs from 'fs';
13import path from 'path';
14
15const QUALITY = '82';
16
17/**
18 * @param {{path:string, filename:string, destination?:string}} file multer file
19 * @returns {string} de definitieve bestandsnaam (basename) — .webp of het origineel
20 */
21export function toWebp(file) {
22 if (!file || !file.path || !file.filename) return file && file.filename;
23 const ext = path.extname(file.filename).toLowerCase();
24 if (ext === '.webp' || ext === '.gif') return file.filename;
25 const dir = file.destination || path.dirname(file.path);
26 const outName = path.basename(file.filename, ext) + '.webp';
27 const outPath = path.join(dir, outName);
28 try {
29 execFileSync('cwebp', ['-quiet', '-q', QUALITY, file.path, '-o', outPath], { stdio: 'ignore' });
30 if (!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) throw new Error('lege output');
31 try { fs.unlinkSync(file.path); } catch { /* origineel weg, niet kritisch */ }
32 return outName;
33 } catch (e) {
34 console.warn('[webp] conversie overgeslagen (cwebp niet beschikbaar/fout):', e.message);
35 try { if (fs.existsSync(outPath)) fs.unlinkSync(outPath); } catch {} // ruim halve output op
36 return file.filename; // behoud origineel
37 }
38}
39
40export default { toWebp };
Note: See TracBrowser for help on using the repository browser.