# Trim borders

## Overview

`trim` automatically removes **solid-color borders** around an image (such as white margins on product photos or gray backgrounds on screenshots) or **transparent edges** (such as excess transparent canvas left over from a PNG export). It detects the minimum bounding rectangle of the content and then crops the image to that rectangle.

> **Tip**
>
> So that output dimensions match what you expect from parameters that **change image size or aspect ratio**, such as `w/h/rect/dpr`, this parameter runs before all such processing.

All four modes share the same detection framework. They differ **only in the predicate that decides whether a pixel counts as background**:

| Mode               | Predicate                                                                                                                             |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `color`            | Difference between the pixel and the specified color ≤ `trim-tol` → background                                                        |
| `auto`             | Mean difference of the row/column from the auto-detected background color ≤ `trim-md` and standard deviation ≤ `trim-sd` → background |
| `alpha`            | `alpha ≤ trim-alpha` → background                                                                                                     |
| `colorunlessalpha` | Same as `alpha` if there is an alpha channel; otherwise same as `auto`                                                                |

Cropping always reuses the `region` pipeline, so **GainMaps and watermarks stay in sync automatically** (see §5).

## Parameter reference

6 parameters in total: 1 mode switch + 5 tuning parameters.

| Parameter    | Default              | Range                                              | Applies to mode | In one sentence                                     |
| ------------ | -------------------- | -------------------------------------------------- | --------------- | --------------------------------------------------- |
| `trim`       | None (no trimming)   | `auto` \| `color` \| `alpha` \| `colorunlessalpha` | —               | Mode switch. If omitted, the feature is not enabled |
| `trim-color` | None (= auto-detect) | `RGB` / `RRGGBB` hex                               | `color`         | Background color to remove                          |
| `trim-tol`   | `10`                 | `0` \~ `255`                                       | `color`         | Color tolerance                                     |
| `trim-md`    | `11`                 | `0` \~ `255`                                       | `auto`          | Mean difference threshold                           |
| `trim-sd`    | `10`                 | `0` \~ `255`                                       | `auto`          | Standard deviation threshold                        |
| `trim-alpha` | `0`                  | `0` \~ `255`                                       | `alpha`         | Alpha threshold                                     |

> **Warning**
>
> **Parameters are mode-specific**:
>
> - `trim-tol` only takes effect in `color` mode
> - `trim-md`/`trim-sd` only take effect in `auto` mode
> - `trim-alpha` only takes effect in `alpha` mode. Parameters passed to a non-matching mode are silently ignored.

## Examples

### Trim a video frame

Original image (with black bars at the top and bottom)

![Original image](https://demo.bitiful.com/trim/The-Princess-and-the-Pilot-5586914.png)

After automatic trimming with `trim=auto`

![Original image](https://demo.bitiful.com/trim/The-Princess-and-the-Pilot-5586914.png?trim=auto)

### Trim a logo / icon

Original image (with white margins on all sides)

![Original image](https://demo.bitiful.com/trim/white_box.png)

After automatic trimming with `trim=auto`

![Original image](https://demo.bitiful.com/trim/white_box.png?trim=auto)

---

## Parameter details

### `trim`: mode switch

If this parameter is omitted, no trimming is performed. It accepts four values:

#### `auto` (recommended default)

Automatically detects the background color (using **the median of 8×8 blocks at the four corners**, which is robust to minor noise and JPEG block artifacts), then classifies background edges using **row/column statistics**: a row or column is treated as background only if both its "mean difference from the background ≤ `trim-md`" and its "standard deviation of internal variation ≤ `trim-sd`".

Best for: photo margins, scanned documents, and background edges with slight compression noise or gradients. Statistical classification is more robust than per-pixel matching.

#### `color`

Removes edges matching the specified `trim-color` within a tolerance of ±`trim-tol`. If `trim-color` is not provided, it falls back to auto-detecting the background color.

Best for: cases where you know exactly what the background color is (such as product photos on a uniform white background) and need precise control over the tolerance.

#### `alpha`

Removes transparent edges where `alpha ≤ trim-alpha`. **If the source image has no alpha channel, this is a no-op** (the image is returned unchanged, without an error).

Best for: PNG, WebP, and other images with an alpha channel, to remove excess transparent canvas.

#### `colorunlessalpha`

Chooses automatically: uses `alpha` when the source image **has an alpha channel**, and `auto` otherwise.

Best for: general-purpose cases where you don't know the input format in advance (such as mixed user-uploaded assets).

---

### `trim-color`: background color

- **Default**: none (falls back to auto-detection)
- **Format**: hexadecimal, as a 3-digit `RGB` shorthand or 6-digit `RRGGBB`, with an optional `#` prefix
- **Examples**: `fff`, `ffffff`, `e9e9e9`, `%23e9e9e9` (`#` must be escaped in URLs)
- **Applies to mode**: `color`

Specifies the background color to remove. If the format is invalid, a warning is logged and it falls back to auto-detection; the request does not fail.

---

### `trim-tol`: color tolerance

- **Default**: `10`
- **Range**: `0` \~ `255`
- **Applies to mode**: `color`

A pixel is treated as background if its difference from the background color on **every channel** is ≤ this value.

- **Lower** (such as `0`\~`5`): removes only pixels that almost exactly match the background color. Suited to the perfectly flat backgrounds of composited images.
- **Higher** (such as `20`\~`40`): tolerates compression noise and slight color casts. Values that are too high may mistakenly crop light-colored content close to the background color.

> When the background is **perfectly flat** (such as a design export), the tolerance value matters little. In one test image, changing `trim-tol` from 5 to 40 changed the result by only 1px, because the content contrasts strongly with the background and the threshold lands on the same boundary wherever it is set. Tolerance really matters for "light-colored content close to the background color" or "dirty edges."

---

### `trim-md`: mean difference threshold

- **Default**: `11`
- **Range**: `0` \~ `255`
- **Applies to mode**: `auto`

A row or column **may** be treated as a background edge only if its **mean difference** from the background color is ≤ this value. It governs "overall shift": background gradients, lens vignetting, and overall color casts.

- **Lower**: requires background edges to be closer to the detected reference color, making classification stricter (more conservative cropping).
- **Higher**: tolerates more pronounced gradient backgrounds (more aggressive cropping).

---

### `trim-sd`: standard deviation threshold

- **Default**: `10`
- **Range**: `0` \~ `255`
- **Applies to mode**: `auto`

A row or column **may** be treated as a background edge only if the **standard deviation** of its internal variation is ≤ this value. It governs "internal fluctuation": noise, texture, and detail.

- **Lower**: requires background edges to be more uniform internally (more conservative cropping).
- **Higher**: tolerates more noise (more aggressive cropping).

> **`trim-md` and `trim-sd` are combined with AND**: a row or column is treated as background only when **both** conditions are met. The two complement each other: mean difference governs overall shift, and standard deviation governs internal fluctuation. An edge with a noticeable but smooth gradient is stopped by `trim-md`; an edge with the right overall color but full of noise is stopped by `trim-sd`.

---

### `trim-alpha`: alpha threshold

- **Default**: `0`
- **Range**: `0` \~ `255`
- **Applies to mode**: `alpha`

A pixel counts as content only if its alpha is **greater than** this value. The default `0` means any pixel that is **not fully transparent** (alpha ≥ 1) is content.

- **Default `0`**: **conservative and safe**. All semi-transparent pixels (feathering, drop shadows, fades, and other artistic effects) are kept, and only fully transparent (alpha = 0) edges are removed.
- **Higher** (such as `8`): for cases where some export tools leave alpha=1\~2 noise residue on edges that "should be fully transparent." This is an explicit choice on your part.

> trim is a **pure crop operation**. It only removes rectangular edges and **does not modify any retained pixels**. Semi-transparent content does not change its transparency because of trim.

---

## Pipeline order

**trim runs before all processing that may change dimensions**:

```text
frame seek → trim → percentage resolution → rect → resize → sharpen/blur → rotate → watermark → encode output
             ↑
     borders removed here
```

This has two direct consequences:

1. **All subsequent operations apply to the trimmed image**. `trim=auto&w=300` means "remove borders first, then resize to 300 based on the trimmed aspect ratio."
2. **Percentage parameters are based on the trimmed dimensions**. In `trim=auto&w=50%`, 50% is half the trimmed width, not half the original width. The same applies to `rect=10%,10%,80%,80%`.
