Normalize mixed color input

Turn heterogeneous concrete colors into one declared space and one reparsable representation.

#806eaeoklch(0.581141 ...)
rgb(217 119 6 / 0.75)oklch(0.66584 ... / 0.75)
color(display-p3 0.82 0.23 0.18)oklch(0.589501 ...)

Make mixed input predictable for the next system

Hex, OKLCH, and Display P3 can enter together and leave as a keyed set of OKLCH values. The application chooses the canonical space instead of inheriting whichever notation arrived.

Declare the destination once

Parse each supported value, convert it into the chosen space, then use that object's native formatter. The same path handles every entry.

<?php

use PhpColor\Color\Color;

$inputs = [
    '#806eae',
    'rgb(217 119 6 / 0.75)',
    'color(display-p3 0.82 0.23 0.18)',
];

$normalized = array_map(
    fn (string $value): string => Color::from($value)
        ->to('oklch')
        ->toCss(),
    $inputs,
);

// oklch(0.581141 0.0979163 296.154)
// oklch(0.66584 0.157422 58.3183 / 0.75)
// oklch(0.589501 0.223108 28.4628)
use PhpColor\Color\Color; $inputs = [ '#806eae', 'rgb(217 119 6 / 0.75)', 'color(display-p3 0.82 0.23 0.18)', ]; $normalized = array_map( fn (string $value): string => Color::from($value) ->to('oklch') ->toCss(), $inputs, ); // oklch(0.581141 0.0979163 296.154) // oklch(0.66584 0.157422 58.3183 / 0.75) // oklch(0.589501 0.223108 28.4628)

Keep application keys attached to normalized colors

A keyed palette can preserve names such as brand, accent, and wide while every value adopts the same coordinate system and CSS syntax.

brandoklch(0.581141 ...)
accentoklch(0.66584 ... / 0.75)
wideoklch(0.589501 ...)

Canonical does not mean lossless

Formatting uses finite precision, while RGB and hexadecimal reduce values more aggressively. Choose normalization for a declared consumer and verify the reparsed representation used by that consumer.

Native CSSKeeps the selected concrete space visible.
HexConverts through sRGB and rounds to bytes.
AlphaMust remain part of the chosen storage contract.
Round tripVerify the exact representation another system receives.

Continue

Normalize a real color collection