oimage
v3.0.0
Published
Interactive terminal UI to optimize images anywhere in your project: same-format recompression (png→png, jpg→jpg), visually lossless per-image quality search with a transparency-aware SSIM check, smart PNG palettes, responsive srcset generation, increment
Maintainers
Readme
oimage
An interactive terminal UI for optimizing images anywhere in your project.
Recompresses in the same format by default — png stays png, jpg stays jpg — so nothing in your markup breaks. Convert to WebP/AVIF only when you ask for it.
Visually lossless by default. Each image gets the lowest quality that still matches the original, measured with a transparency-aware SSIM check — flat logos shrink hard, detailed photos keep what they need, and transparent PNGs never gain a background.
┌─ oimage ──────────────────────────────── 5 images · 917 KB · ./public ─┐
│ │
│ ❯ ▾ icons/ 2 img 3.8 KB │
│ [x] logo.png 3.2 KB │
│ [x] tiny.png 667 B │
│ ▾ images/ 3 img 913 KB │
│ [x] card.png 632 KB │
│ [x] hero.jpg 280 KB │
│ │
│ mode visually lossless format same quality auto ≤95 png smart ... │
│ selected 5 files · 917 KB │
│ │
│ ℹ mode: visual Every image is compressed as far as it can go without │
│ any visible change, transparency included. │
│ │
│ ↑↓ move · space pick · v mode · f format · p png · [ ] quality · │
│ r resize · w srcset · m output · d preview · ↵ run · ? keys · q quit │
└────────────────────────────────────────────────────────────────────────┘Every time you change a setting, the ℹ line says what that setting will
actually do to your files — no need to remember what "ssim" or "palette" mean.
Press ? for a plain-language list of every key.
Install
npm install --save-dev oimage
npx oimgOr globally:
npm install -g oimage
oimgRequires Node.js 22+. The command is oimg; optimize-images and
optimize-public are aliases for the same binary.
Usage
oimg # full-screen UI, auto-detects where images live
oimg ./src/assets # scan a specific directory
oimg --dry-run # report projected savings, write nothingFolders nest properly: a deep asset tree opens as a handful of top-level rows,
each showing the recursive image count and byte total, and ticking a folder
ticks everything beneath it ([~] means partly selected). Single-child chains
are merged, so a/ > b/ > c/ shows as one a/b/c/ row.
Nothing is selected to begin with — pick files with space (on a folder it
takes everything beneath), or a for all. Fold folders with ←→, tune settings
live in the status bar, and press d to preview savings before ↵ commits
anything. Nothing is written until you press ↵, and
overwriting originals asks for confirmation first.
| Key | |
|---|---|
| ↑↓ ←→ space a | Move, open/close a folder, tick one, tick all |
| v | Mode — maximum / visually lossless / balanced / smallest |
| f | Output format — keep the same one, or convert to WebP/AVIF |
| p | PNG — smart / lossless / 256-colour palette |
| [ ] | Fixed quality down / up by 5 (instead of a mode) |
| r | Shrink anything wider than a chosen limit |
| w | Generate phone/tablet/desktop sizes and the srcset markup |
| s | Fine-tune how closely results must match the original |
| m b n | Where files go, keep .bak copies, how many at once |
| c | Skip images already optimized, or re-do every one |
| d | Dry run — show what would be saved, change nothing |
| ↵ | Start optimizing |
| ? | Explain every key |
| q | Quit |
Headless / CI
Pass --yes or --dry-run and it skips the UI entirely:
oimg ./public --preset visual --max-width 1920 --yes
oimg --json > report.jsonExit codes: 0 success, 1 some files failed, 2 bad arguments or a refused run.
Options
| Option | Default | |
|---|---|---|
| [directory] | auto | Inside a project, scans public//static//assets//src/assets/ if present. Anywhere else, scans the current folder |
| --preset <p> | visual | max | visual | balanced | small — per-image automatic quality (see below) |
| --format <f> | same | same | webp | avif | jpeg | png |
| -q, --quality <n> | | Fixed quality 1–100 for every file instead of a preset |
| --max-width <n> | off | Downscale anything wider; aspect ratio preserved, never upscales |
| --widths <list> | off | Emit responsive variants, e.g. 640,1024,1920, and print the <img srcset> |
| --min-ssim <n> | per preset | Fine-tune the match target, 0–1 |
| --max-quality <n> | per preset | Highest quality the search may use |
| --png <m> | smart | smart | lossless | palette |
| --png-palette | | Same as --png palette |
| --background <hex> | #ffffff | Fill for transparent pixels, JPEG output only |
| --keep-metadata | off | Preserve EXIF/ICC (stripped by default) |
| --mode <m> | folder | folder | in-place | suffix |
| --out <dir> | optimized | Output folder for --mode folder |
| --suffix <s> | .min | Filename suffix for --mode suffix |
| --backup | off | Keep a .bak copy when overwriting in place |
| -j, --jobs <n> | cpus (max 8) | Parallel encodes |
| --no-gitignore | | Scan files .gitignore excludes |
| -y, --yes | | Headless |
| --dry-run | | Report only |
| --json | | Machine-readable output, implies headless |
| --watch | | Stay running and optimize images as they appear |
| --force, --redo | | Re-optimize every image, including already-done ones (alias: --no-cache) |
| --prune | | Delete outputs left by renamed or deleted sources |
| --config <path> | | Use a specific config file |
| --no-config | | Ignore any oimg.config.json / package.json "oimage" |
Responsive images
Serving a 1920px hero to a phone wastes more bytes than any encoder setting can
recover. --widths emits one file per breakpoint and prints the markup:
oimg --widths 640,1024,1920 -y✓ images/hero.jpg 280 KB → 83 KB -70%
320w 16 KB hero-320.jpg
640w 46 KB hero-640.jpg
960w 83 KB hero-960.jpg
<img
src="/optimized/images/hero-640.jpg"
srcset="/optimized/images/hero-320.jpg 320w,
/optimized/images/hero-640.jpg 640w,
/optimized/images/hero-960.jpg 960w"
sizes="100vw"
width="960"
alt=""
/>Widths larger than the source are dropped rather than upscaled. Savings are
reported at the largest variant — what a full-width visitor actually
downloads — with the total disk cost shown separately. Animations stay
single-variant. Set sizes yourself: the browser cannot infer your layout, and
a wrong sizes quietly defeats the point of srcset.
Quality modes
One global quality is a blunt instrument — the setting that leaves a photo pristine visibly wrecks a gradient, and wastes bytes on a logo. So by default there is no single quality: for each image oimage binary-searches for the lowest quality whose result still scores at least the mode's target against the original.
| Mode (v, --preset) | Target | PNG | Use it for |
|---|---|---|---|
| max | 0.995 | lossless | Brand assets, anything you will zoom into |
| visual (default) | 0.99 | smart | Everything: no visible change |
| balanced | 0.98 | smart | A little smaller, differences only side by side |
| small | 0.95 | smart | Thumbnails, backgrounds, bandwidth-critical pages |
| custom | — | — | -q 75: the same fixed quality for every file |
Real output from an app's artwork folder (--preset visual):
✓ instagram.png 518 KB → 97 KB -81% ssim 0.997 ← smart PNG palette
✓ face_male.png 716 KB → 246 KB -66% ssim 0.996
✓ profile_photo.jpg 104 KB → 74 KB -29% q68 ssim 0.991
✓ logo.png 2.6 MB → 2.2 MB -16% ← gradients: kept losslessTransparency counts. For images with an alpha channel the score is the worst of: luma over white, luma over black, and the alpha channel itself. A result that frays edges or fills transparent areas fails the check.
Smart PNG. Each PNG is tried as a 256-colour palette; that version is kept only when it passes the same check and is smaller — logos and icons shrink by 60–90%, photos and gradients stay pixel-for-pixel lossless.
No backgrounds added. PNG, WebP and AVIF keep transparency exactly. An
alpha channel where every pixel is opaque is dropped (no pixel changes, smaller
file). Only JPEG — which cannot store transparency — gets a fill, white by
default (--background), never black.
A deliberate resize is compared against the resized original, so downscaling
is never mistaken for encoder damage. If even --max-quality misses the
target, that quality is used and the run says so.
Incremental cache
Re-runs skip untouched files, which is what makes this viable in a pre-commit hook or CI step rather than a once-in-a-while manual run.
$ oimg -y
Up to date — 5 files already optimized (728 KB saved, -79%)Turn it off to redo everything — c in the UI, or --redo / --force on the
command line. Useful after changing a file outside the tool, or to rebuild an
output folder from scratch.
It works in two tiers. First a cheap check — same path, same size, same
timestamp, outputs still on disk — which costs one stat and never opens the
image. If that misses, the file's contents are hashed and matched against what
has been encoded before, so these all skip the encoder too:
| | |
|---|---|
| git checkout / touch | Timestamp changed, bytes didn't |
| A renamed or moved image | The existing output is copied to the new name |
| A duplicate of an image already in the project | Encoded once, reused everywhere |
The cache lives in .oimg-cache.json at the scan root and stores only relative
paths, so you can commit it and let CI or a teammate skip the same work. It
invalidates when the source bytes change, when any setting that affects output
bytes changes, or when an output it claims to have written has gone missing.
What it deliberately does not do is inspect an arbitrary image and guess
whether someone already compressed it — that guess is unreliable, and guessing
wrong means silently shipping an unoptimized file. Instead there is a safety net
that needs no cache at all: if re-encoding would produce a larger file and the
format is unchanged, the original is kept and reported as already optimal. So
running against previously-optimized images is safe even on a fresh machine —
it just costs the encode time to find out.
Stale outputs
Renaming or deleting a source leaves its old output behind. Those are reported
after each run, and --prune removes them:
1 stale output (86 KB) left by renamed or deleted sources,
e.g. optimized/images/card.png — run with --prune to remove them.Watch mode
oimg --watchRe-runs on changes, debounced and serialised so a burst of saves cannot start overlapping runs. Combined with the cache, each trigger only touches what moved.
Config file
Drop an oimg.config.json (or .oimgrc.json, or an "oimage" key in
package.json) anywhere above the scan directory:
{
"format": "same",
"quality": 78,
"maxWidth": 1920,
"widths": [640, 1024, 1920],
"minSsim": 0.95,
"outputDir": "optimized"
}CLI flags win over the file, but only flags you actually typed — an untouched
default never silently overrides a value the project set. Unknown keys are
reported rather than ignored, so qualty is an error, not a no-op.
What it does that a plain sharp call doesn't
Never makes a file worse. Re-encoding isn't guaranteed to win — small PNGs and
already-optimised JPEGs routinely come out larger. When the format is unchanged
and the result would grow, the original is kept and reported as already optimal.
In folder mode the original is copied across so the output tree stays complete.
Same format means same format. JPEG goes through mozjpeg (10–20% smaller than
libjpeg at identical quality). PNG is lossless, or a 256-colour palette only where that
looks identical (--png lossless to never quantise). Your <img src="hero.jpg"> keeps working.
Keeps animation. Animated GIFs keep every frame, and stay animated through a WebP conversion. Asking for a still-only format on an animated source keeps the original container rather than silently discarding all but frame one.
Applies EXIF orientation before stripping it. Stripping metadata without baking in the orientation tag rotates images for every viewer. Metadata is stripped by default, which also keeps GPS coordinates out of your public folder.
Refuses to clobber. hero.jpg and hero.png both become hero.webp — that's
silent data loss, so the run is refused with the conflicting paths listed.
Won't eat its own output. A second run ignores optimized/ and already-suffixed
files, so repeated runs don't compound lossy generations or produce hero.min.min.jpg.
The cache also remembers every path it has ever written, so renaming the output
folder doesn't turn the old one into scannable input.
Stays inside the folder you point it at. Symlinked directories are not
followed, and a symlink to a file outside the root is skipped rather than
read — otherwise in-place mode would write straight through it and modify a
file outside your project. An output folder that escapes the root
(--out ../elsewhere, or the same value from a config file) is refused.
Won't scan your home directory. Run it somewhere far too broad — ~, /,
/Volumes — and it stops and offers you a folder instead of walking photo
libraries, caches and network mounts. Headless refuses outright, since there is
nobody to ask. Naming a path explicitly always wins: oimg ~/whatever does what
you asked.
Won't wander into node_modules. Build output, VCS directories and
.gitignored paths are skipped. SVGs are never touched — sharp would rasterise
them into a fixed-size bitmap and destroy the vector. Scanning streams and
reports progress, so a large tree never looks like a hang.
Writes atomically. Encodes to a temp file and renames, so a crash or a full disk leaves the original intact rather than truncated.
Programmatic API
import { optimize } from 'oimage';
const { summary } = await optimize({
root: './public',
format: 'same',
quality: 75,
maxWidth: 1920,
dryRun: true,
onResult: (r) => console.log(r.file.relative, r.inputSize, '→', r.outputSize),
});
console.log(`saved ${summary.savedBytes} bytes across ${summary.done} files`);Also exported: scan, detectRoot, encode, plan, findCollisions, summarise, defaultSettings.
Development
npm install
npm run build # esbuild → dist/
npm run dev # watch mode
npm test # node:test, real images through real encodersMigrating from optimize-public-images
This package was previously published as optimize-public-images. Changes:
- Scans any directory, not just
public/. The old auto-detection is still the default. - Defaults to same-format recompression instead of always converting to WebP. Pass
--format webpfor the old behaviour. Replace original filesused to write a.webpalongside the original without replacing anything.--mode in-placenow genuinely overwrites, behind a confirmation.- The command is now
oimg, but the oldoptimize-publicbinary name still works.
License
MIT
