Intervention/image · error · InvalidArgumentException

Invalid trim tolerance. Must be int<0, max>

Error message

Invalid trim tolerance. Must be int<0, max>

What it means

TrimModifier backs $image->trim($tolerance) and removes a uniform border around the image; tolerance defines how much neighboring colors may deviate from the border color and still get trimmed. It must be a non-negative int (int<0, max> in PHPStan range notation); a negative tolerance has no meaning, so the constructor throws InvalidArgumentException.

Source

Thrown at src/Modifiers/TrimModifier.php:20

declare(strict_types=1);

namespace Intervention\Image\Modifiers;

use Intervention\Image\Drivers\SpecializableModifier;
use Intervention\Image\Exceptions\InvalidArgumentException;

class TrimModifier extends SpecializableModifier
{
    /**
     * Create new modifier object.
     *
     * @throws InvalidArgumentException
     */
    public function __construct(public int $tolerance = 0)
    {
        if ($this->tolerance < 0) {
            throw new InvalidArgumentException('Invalid trim tolerance. Must be int<0, max>');
        }
    }
}

View on GitHub (pinned to 5598b9e397)

Solutions

  1. Clamp the tolerance before calling: $image->trim(max(0, $tolerance))
  2. Validate config/user input for trim tolerance as int >= 0 and reject or normalize negatives
  3. If a negative input means 'do not trim', skip the trim() call when the value is negative

Example fix

// before
$image->trim($settings['trim_tolerance']);

// after
$image->trim(max(0, (int) $settings['trim_tolerance']));
Defensive patterns

Strategy: validation

Validate before calling

// Clamp trim tolerance before calling
$tolerance = max(0, (int) $settings['trim_tolerance']);
$image->trim($tolerance);

Type guard

function isValidTrimTolerance(mixed $tolerance): bool
{
    return is_int($tolerance) && $tolerance >= 0;
}

Try / catch

use Intervention\Image\Exceptions\InvalidArgumentException;

try {
    $image->trim($tolerance);
} catch (InvalidArgumentException $e) {
    // message: 'Invalid trim tolerance. Must be int<0, max>'
    $image->trim(0);
}

Prevention

When it happens

Trigger: Calling $image->trim(-1) or $image->trim(tolerance: $config['tolerance']) where the config value is negative. Also new TrimModifier(-5) directly.

Common situations: Config files with mistyped negative tolerances; user-facing 'trim sensitivity' inputs where higher sensitivity was mapped to negative numbers; tolerance values passed through arithmetic that can go below zero.

Related errors


AI-assisted analysis of Intervention/image@5598b9e397 (2026-08-23). Data as JSON: /api/errors/b6d3ad7835fad357. Report an issue: GitHub.