# Trim borders

## Overview

`trim` automatically removes **solid-color borders** (such as the white padding around product photos or the gray background in screenshots) or **transparent borders** (such as extra transparent canvas left over from PNG exports) around an image. It detects the smallest rectangle that encloses the content, then crops the image to that rectangle.

> **Warning**
>
> To honor the expected output dimensions of parameters that **change image size or aspect ratio**, such as `w/h/rect/dpr`, this parameter is applied before all such processing.

| Mode               | Background test                                                                                                                |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| `color`            | Pixel difference from the specified color ≤ `trim-tol` → background                                                            |
| `auto`             | Row/column mean difference 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`                                                         |

## Parameter reference

| Parameter    | Default              | Range                                              | Applies to mode | Summary                                             |
| ------------ | -------------------- | -------------------------------------------------- | --------------- | --------------------------------------------------- |
| `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 trim                            |
| `trim-tol`   | `10`                 | `0` to `255`                                       | `color`         | Color tolerance                                     |
| `trim-md`    | `11`                 | `0` to `255`                                       | `auto`          | Mean difference threshold                           |
| `trim-sd`    | `10`                 | `0` to `255`                                       | `auto`          | Standard deviation threshold                        |
| `trim-alpha` | `0`                  | `0` to `255`                                       | `alpha`         | Alpha threshold                                     |

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

## Examples

### Trim a video frame

Original (with black bars at the top and bottom)

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

After automatic trimming with `trim=auto`

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

### Trim logos and icons

Original (with white borders on all sides)

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

After automatic trimming with `trim=auto`

![Original](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 the 8×8 blocks in the four corners**, which is robust against minor noise and JPEG block artifacts), then identifies background edges using **row/column statistics**: a row or column is treated as background only if its mean difference from the background is ≤ `trim-md` and the standard deviation of its internal variation is ≤ `trim-sd`.

Best for: whitespace around photos, scanned documents, and background borders with slight compression noise or gradients. Statistical detection is more robust than per-pixel matching.

#### `color`

Trims borders that match the specified color `trim-color` within a tolerance of ±`trim-tol`. If `trim-color` isn't 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`

Trims transparent borders where `alpha ≤ trim-alpha`. **If the source image has no alpha channel, this is a no-op** (the image is returned unchanged, with no error).

Best for: images with an alpha channel, such as PNG and WebP, to remove extra transparent canvas.

#### `colorunlessalpha`

Smart selection: uses `alpha` if 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 uploads).

---

### `trim-color` — background color

- **Default**: none (falls back to auto-detection)
- **Format**: hex, either 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 trim. If the format is invalid, a warning is logged and trimming falls back to auto-detection; the request doesn't fail.

---

### `trim-tol` — color tolerance

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

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

- **Lower** (such as `0`–`5`): trims only pixels that almost exactly match the background color. Suited to perfectly flat backgrounds in composited images.
- **Higher** (such as `20`–`40`): tolerates compression noise and slight color casts. Set it too high, however, and light-colored content close to the background color may be trimmed by mistake.

> When the background is **perfectly flat** (such as in design exports), the tolerance value makes little difference. In one test, changing `trim-tol` from 5 to 40 changed the result by just 1px: the content contrasts so strongly with the background that the threshold lands on the same boundary either way. Tolerance really matters for light-colored content close to the background color, or for dirty edges.

---

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

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

A row or column **can** 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 detection stricter (more conservative trimming).
- **Higher**: tolerates more pronounced background gradients (more aggressive trimming).

---

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

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

A row or column **can** 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 (more conservative trimming).
- **Higher**: tolerates more noise (more aggressive trimming).

> **`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: the mean difference governs overall shift, and the standard deviation governs internal fluctuation. An edge with a pronounced but smooth gradient is rejected by `trim-md`; an edge with the right overall color but full of noise is rejected by `trim-sd`.

---

### `trim-alpha` — alpha threshold

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

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

- **Default `0`**: **conservative and safe**. All semi-transparent pixels (feathering, drop shadows, fades, and other artistic effects) are preserved; only fully transparent (alpha = 0) edges are trimmed.
- **Higher** (such as `8`): for cases where certain export tools leave alpha=1–2 noise residue on edges that should be fully transparent. This is an explicit choice on the user's part.

> trim is a **pure crop operation**: it only removes rectangular edges and **doesn't modify any of the pixels it keeps**. Semi-transparent content keeps its original opacity after trimming.

---

## Pipeline order

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

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

This has two direct consequences:

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