Standardize public images on WebP and add conversion tooling
All checks were successful
Deploy Sokko G / deploy (push) Successful in 20s
All checks were successful
Deploy Sokko G / deploy (push) Successful in 20s
This commit is contained in:
parent
75592d7d7a
commit
ca39b76282
883 changed files with 503 additions and 90 deletions
152
scripts/convert-public-images.mjs
Normal file
152
scripts/convert-public-images.mjs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// Rôle : convertit des PNG publics vers le format WebP canonique du site.
|
||||
import { spawn } from "node:child_process";
|
||||
import { readdir, rename, rm, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
const PRESETS = new Set(["default", "picture", "photo", "drawing", "icon", "text"]);
|
||||
const options = {
|
||||
allowLarger: false,
|
||||
dryRun: false,
|
||||
force: false,
|
||||
lossless: false,
|
||||
preset: "picture",
|
||||
keepSource: false,
|
||||
quality: 90
|
||||
};
|
||||
const inputs = [];
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage: npm run images:convert -- <fichier-ou-dossier...> [options]
|
||||
|
||||
Convertit récursivement les fichiers PNG en WebP dans le même dossier.
|
||||
Chaque PNG source est supprimé après une conversion réussie.
|
||||
|
||||
Options :
|
||||
--quality=<1-100> Qualité avec pertes (défaut : 90)
|
||||
--preset=<nom> default, picture, photo, drawing, icon ou text
|
||||
--lossless Utilise WebP sans perte ; ignore quality et preset
|
||||
--allow-larger Accepte un WebP plus lourd que le PNG source
|
||||
--keep-source Conserve le PNG source pour une comparaison ponctuelle
|
||||
--force Remplace un WebP déjà présent
|
||||
--dry-run Affiche les conversions sans écrire de fichier
|
||||
--help Affiche cette aide`);
|
||||
}
|
||||
|
||||
for (const argument of process.argv.slice(2)) {
|
||||
if (argument === "--help" || argument === "-h") {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
} else if (argument === "--allow-larger") options.allowLarger = true;
|
||||
else if (argument === "--dry-run") options.dryRun = true;
|
||||
else if (argument === "--force") options.force = true;
|
||||
else if (argument === "--lossless") options.lossless = true;
|
||||
else if (argument === "--keep-source") options.keepSource = true;
|
||||
else if (argument.startsWith("--quality=")) options.quality = Number(argument.slice("--quality=".length));
|
||||
else if (argument.startsWith("--preset=")) options.preset = argument.slice("--preset=".length);
|
||||
else if (argument.startsWith("--")) throw new Error(`Option inconnue : ${argument}`);
|
||||
else inputs.push(argument);
|
||||
}
|
||||
|
||||
if (!Number.isInteger(options.quality) || options.quality < 1 || options.quality > 100) {
|
||||
throw new Error("--quality doit être un entier compris entre 1 et 100.");
|
||||
}
|
||||
if (!PRESETS.has(options.preset)) throw new Error(`Preset WebP inconnu : ${options.preset}`);
|
||||
if (inputs.length === 0) {
|
||||
printHelp();
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
await convertInputs();
|
||||
}
|
||||
|
||||
async function collectPngFiles(input) {
|
||||
const inputPath = path.resolve(input);
|
||||
const inputStat = await stat(inputPath);
|
||||
if (inputStat.isFile()) {
|
||||
if (!inputPath.toLowerCase().endsWith(".png")) throw new Error(`Le fichier n'est pas un PNG : ${input}`);
|
||||
return [inputPath];
|
||||
}
|
||||
if (!inputStat.isDirectory()) throw new Error(`Entrée non prise en charge : ${input}`);
|
||||
|
||||
const entries = await readdir(inputPath, { withFileTypes: true });
|
||||
return (await Promise.all(entries.map((entry) => {
|
||||
const entryPath = path.join(inputPath, entry.name);
|
||||
if (entry.isDirectory()) return collectPngFiles(entryPath);
|
||||
return entry.isFile() && entry.name.toLowerCase().endsWith(".png") ? [entryPath] : [];
|
||||
}))).flat();
|
||||
}
|
||||
|
||||
function runFfmpeg(argumentsList) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn("ffmpeg", argumentsList, { stdio: ["ignore", "ignore", "pipe"] });
|
||||
let stderr = "";
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
||||
child.once("error", (error) => reject(error.code === "ENOENT" ? new Error("ffmpeg est requis pour convertir les images.") : error));
|
||||
child.once("close", (code) => code === 0 ? resolve() : reject(new Error(stderr.trim() || `ffmpeg a quitté avec le code ${code}.`)));
|
||||
});
|
||||
}
|
||||
|
||||
async function convertImage(source) {
|
||||
const target = source.replace(/\.png$/i, ".webp");
|
||||
const relativeSource = path.relative(process.cwd(), source);
|
||||
const relativeTarget = path.relative(process.cwd(), target);
|
||||
try {
|
||||
await stat(target);
|
||||
if (!options.force) {
|
||||
console.log(`Ignoré : ${relativeTarget} existe déjà (utiliser --force pour le remplacer).`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
}
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log(`[simulation] ${relativeSource} -> ${relativeTarget}${options.keepSource ? "" : " puis suppression du PNG"}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const temporaryTarget = `${target}.${process.pid}.tmp.webp`;
|
||||
const encoding = options.lossless
|
||||
? ["-lossless", "1", "-quality", "100", "-compression_level", "6", "-pix_fmt", "bgra"]
|
||||
: ["-preset", options.preset, "-quality", String(options.quality), "-compression_level", "6"];
|
||||
try {
|
||||
await runFfmpeg(["-y", "-v", "error", "-i", source, "-c:v", "libwebp", ...encoding, temporaryTarget]);
|
||||
const [sourceStat, targetStat] = await Promise.all([stat(source), stat(temporaryTarget)]);
|
||||
if (targetStat.size === 0) throw new Error(`La conversion de ${relativeSource} a produit un fichier vide.`);
|
||||
if (targetStat.size >= sourceStat.size && !options.allowLarger) {
|
||||
await rm(temporaryTarget);
|
||||
console.log(`Conservé : ${relativeSource}, le WebP serait plus lourd (${sourceStat.size} -> ${targetStat.size} octets).`);
|
||||
return null;
|
||||
}
|
||||
await rename(temporaryTarget, target);
|
||||
if (!options.keepSource) await rm(source);
|
||||
console.log(`${relativeSource} -> ${relativeTarget} (${sourceStat.size} -> ${targetStat.size} octets)`);
|
||||
return { sourceBytes: sourceStat.size, targetBytes: targetStat.size };
|
||||
} catch (error) {
|
||||
await rm(temporaryTarget, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function convertInputs() {
|
||||
const collected = (await Promise.all(inputs.map(collectPngFiles))).flat();
|
||||
const sources = [...new Set(collected)].sort((left, right) => left.localeCompare(right, "fr"));
|
||||
if (sources.length === 0) {
|
||||
console.log("Aucun fichier PNG trouvé.");
|
||||
return;
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (const source of sources) {
|
||||
const result = await convertImage(source);
|
||||
if (result) results.push(result);
|
||||
}
|
||||
if (options.dryRun || results.length === 0) return;
|
||||
|
||||
const sourceBytes = results.reduce((total, result) => total + result.sourceBytes, 0);
|
||||
const targetBytes = results.reduce((total, result) => total + result.targetBytes, 0);
|
||||
const difference = Math.abs((sourceBytes - targetBytes) * 100 / sourceBytes).toFixed(1);
|
||||
const evolution = targetBytes <= sourceBytes ? `${difference} % de moins` : `${difference} % de plus`;
|
||||
console.log(`${results.length} image(s) convertie(s) : ${sourceBytes} -> ${targetBytes} octets (${evolution}).`);
|
||||
if (options.keepSource) console.log("Les PNG source sont conservés pour comparaison.");
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue