Autocrop — trim a transparent or solid-colour border

Finds the smallest rectangle that still contains the actual content and crops to it. Without a colour (AUTO=true) it takes the background from the top-left pixel — transparent margins after a background-removal step, or a flat frame; with COLOR it trims exactly that colour (white frame around a scan, brand background around a logo). PADDING keeps N pixels of breathing room. The example: a 1100×1100 portrait with a 150 px white frame — autocrop strips the frame in one pass.

INPUT
INPUT — Autocrop — trim a transparent or solid-colour border
Frame removed
Frame removed — Autocrop — trim a transparent or solid-colour border
JavaScript
// Trim a uniform-colour or transparent border (img.autocrop)
// demo_autocrop.js
//!INPUT: INPUT
//!OUTPUT: OUTPUT
//!PARAM: COLOR:string=#ffffff
//!PARAM: TOLERANCE:number=0.05,min=0,max=1
//!PARAM: PADDING:integer=0,min=0,max=200
//!PARAM: AUTO:boolean=false

// Finds the smallest rectangle containing every non-background
// pixel and crops to it. Two modes:
//
//   AUTO = true  → no colour given: the background comes from the
//                  top-left pixel. A transparent corner trims transparent
//                  margins (cut-outs from rmbg, any image with alpha), an
//                  opaque one trims its colour (a white frame).
//
//   AUTO = false → trim the supplied COLOR. Per-channel tolerance
//                        in [0, 1] handles JPEG noise / scanner streaks.
//                        Pure-α=0 pixels also count as background, so
//                        mixed transparent + flat-colour frames work
//                        without a second pass.
//
// PADDING keeps N pixels of margin around the detected box (clamped
// to image bounds). Useful when downstream layout expects breathing
// room.
//
// Pipeline-friendly: chain after rmbg / facedetect / writeSVG to keep
// only the actual content.

const img = Engine.loadImage(INPUT);
console.log(`before: ${img.width}×${img.height}`);

if (AUTO) {
    img.autocrop({ tolerance: TOLERANCE, padding: PADDING });
} else {
    img.autocrop({ color: COLOR, tolerance: TOLERANCE, padding: PADDING });
}

console.log(`after:  ${img.width}×${img.height}`);
img.save(OUTPUT);
img.free();

// © 2026 Michael Lechner · mlc OpticScript · https://mlcgo.eu · Elastic License 2.0