import sharp from 'sharp'; import { mkdir } from 'node:fs/promises'; import { dirname, extname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { accentStrength, gradeImage } from './image-palette.mjs'; export const imageDefaults = { width: 960, tones: 0, quality: 75, strength: 0.5, accent: accentStrength, }; const usage = 'Usage: npm run image:prepare -- input.jpg output.avif [--width 960] [--tones 0|2|5|16] [--quality 1..100] [--strength 0..2] [--accent 0..1]'; function options(args) { const [input, output, ...flags] = args; if (!input || !output || extname(output).toLowerCase() !== '.avif' || flags.length % 2) throw new Error(usage); const config = { ...imageDefaults }; for (let i = 0; i < flags.length; i += 2) { const key = flags[i].replace(/^--/, ''); const value = Number(flags[i + 1]); if (!(key in config) || flags[i] !== `--${key}` || !Number.isFinite(value)) throw new Error(usage); config[key] = value; } if ( !Number.isInteger(config.width) || config.width < 1 || ![0, 2, 5, 16].includes(config.tones) || !Number.isInteger(config.quality) || config.quality < 1 || config.quality > 100 || config.strength < 0 || config.strength > 2 || config.accent < 0 || config.accent > 1 ) throw new Error(usage); return { input, output, ...config }; } export async function preprocessImage({ input, output, width, tones, quality, strength, accent }) { const { data, info } = await sharp(input) .rotate() .resize({ width, withoutEnlargement: true }) .greyscale() .raw() .toBuffer({ resolveWithObject: true }); const pixels = gradeImage(data, info.width, info.height, tones, strength, accent); await mkdir(dirname(output), { recursive: true }); await sharp(pixels, { raw: { width: info.width, height: info.height, channels: 3 } }) .avif({ quality, effort: 6 }) .toFile(output); const result = await sharp(output).metadata(); return { width: result.width, height: result.height }; } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const config = options(process.argv.slice(2)); const result = await preprocessImage(config); console.log(`${config.output}: ${result.width}×${result.height}`); }