/** * Downscales JPEG/PNG files in place — used by scripts/seed-content.mjs after it * extracts the base64 heroes out of a studio export (some originals are 8000px * wide and 12MB). * * node scripts/resize-images.mjs [maxWidth] [quality] * * Uses Windows' own imaging stack via PowerShell so the repo needs no native * image dependency. On other platforms it reports what it would have resized — * images uploaded through /admin are downscaled in the browser instead, so this * only affects the one-off import. */ import { execFileSync } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' export function resizeDirectory(dir, maxWidth = 1600, quality = 82) { if (!fs.existsSync(dir)) return const files = fs.readdirSync(dir).filter((f) => /\.(jpe?g|png)$/i.test(f)) const oversized = files.filter((f) => fs.statSync(path.join(dir, f)).size > 600 * 1024) if (!oversized.length) return if (process.platform !== 'win32') { console.warn( ` ! ${oversized.length} large image(s) in ${dir} were left as-is (resizing needs Windows imaging). ` + 'Optimise them before deploying.', ) return } const script = ` Add-Type -AssemblyName System.Drawing $enc = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq 'image/jpeg' } $ps = New-Object System.Drawing.Imaging.EncoderParameters 1 $ps.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter([System.Drawing.Imaging.Encoder]::Quality, ${quality}) Get-ChildItem -LiteralPath '${dir.replace(/'/g, "''")}' -Include *.jpg,*.jpeg,*.png -File -Recurse | ForEach-Object { $img = [System.Drawing.Image]::FromFile($_.FullName) if ($img.Width -le ${maxWidth}) { $img.Dispose(); return } $scale = ${maxWidth} / [double]$img.Width $nw = [int]($img.Width * $scale); $nh = [int]($img.Height * $scale) $bmp = New-Object System.Drawing.Bitmap $nw, $nh $g = [System.Drawing.Graphics]::FromImage($bmp) $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic $g.DrawImage($img, 0, 0, $nw, $nh) $g.Dispose(); $img.Dispose() $tmp = $_.FullName + '.tmp' $bmp.Save($tmp, $enc, $ps); $bmp.Dispose() Move-Item -Force $tmp $_.FullName Write-Output (" resized {0} -> {1}px, {2}KB" -f $_.Name, $nw, [int]((Get-Item $_.FullName).Length/1KB)) }` try { const out = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8' }) if (out.trim()) console.log(out.trimEnd()) } catch (err) { console.warn(` ! image resize failed: ${err.message}`) } } // Standalone use if (process.argv[1] && import.meta.url.endsWith(path.basename(process.argv[1]))) { const [dir, max, quality] = process.argv.slice(2) if (!dir) { console.error('usage: node scripts/resize-images.mjs [maxWidth] [quality]') process.exit(1) } resizeDirectory(path.resolve(dir), Number(max) || 1600, Number(quality) || 82) }