Intervention/image · error · Intervention\Image\Exceptions\InvalidArgumentException

Number of color channels must be 4 or 5 for {class}

Error message

Number of color channels must be 4 or 5 for {class}

What it means

ReduceColorsModifier (quantization / palette reduction) validates that the color limit is at least 1 — a palette with zero colors is meaningless. The constructor throws InvalidArgumentException for any limit < 1.

Source

Thrown at src/Colors/Cmyk/Colorspace.php:46

    public static array $channels = [
        Channels\Cyan::class,
        Channels\Magenta::class,
        Channels\Yellow::class,
        Channels\Key::class,
        Channels\Alpha::class,
    ];

    /**
     * {@inheritdoc}
     *
     * @see ColorspaceInterface::colorFromNormalized()
     *
     * @throws InvalidArgumentException
     */
    public static function colorFromNormalized(array $normalized): CmykColor
    {
        if (!in_array(count($normalized), [4, 5])) {
            throw new InvalidArgumentException('Number of color channels must be 4 or 5 for ' . static::class);
        }

        // add alpha value if missing
        $normalized = count($normalized) === 4 ? array_pad($normalized, 5, 1) : $normalized;

        return new Color(...array_map(
            function (string $channel, null|float $normalized) {
                try {
                    return $channel::fromNormalized($normalized);
                } catch (TypeError $e) {
                    throw new InvalidArgumentException(
                        'Normalized color value must be in range 0 to 1',
                        previous: $e,
                    );
                }
            },
            self::$channels,
            $normalized,

View on GitHub (pinned to 5598b9e397)

Solutions

  1. Treat 0 or less as 'do not quantize' in your wrapper: if ($limit >= 1) { $image->reduceColors($limit); }.
  2. Clamp: max(1, (int) $limit) when reduction must always happen.
  3. Document in your API that the valid range is 1..(driver maximum) and validate at the boundary.

Example fix

// before
$image->reduceColors($colors); // 0 throws

// after
if ($colors >= 1) {
    $image->reduceColors($colors);
}
Defensive patterns

Strategy: validation

Validate before calling

if ($limit >= 1) {
    $image->reduceColors($limit);
}

Prevention

When it happens

Trigger: $image->reduceColors(0); passing a user-supplied 'numberOfColors' of 0; deriving the limit from a subtraction or from config that defaults to 0.

Common situations: Form fields with a 0 default meaning 'unlimited'/'disabled' being forwarded verbatim; dividing user input down (e.g. intdiv($n, 100) with small $n) reaching 0; API consumers assuming 0 disables quantization.

Related errors


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