Preserve Display P3 in a stored CSS token

Store a Display P3 color as CSS, restore it as the same concrete color type, and verify the tested channels and alpha after the round trip.

Use this recipe when a configuration record or design token contains Display P3 coordinates that must not be flattened to hexadecimal at ingestion. It stores the native CSS representation in JSON and restores the tested value as a DisplayP3Color.

This procedure preserves the coordinates and alpha shown below. Treat broader color management and gamut mapping as separate requirements.

Serialize the native CSS value

Parse the Display P3 input and store its native color(display-p3 ...) representation.

use PhpColor\Color\Color;
use PhpColor\Color\DisplayP3Color;

$source = Color::parse(
    'color(display-p3 0.925 0.204 0.137 / 0.8)',
);

assert($source instanceof DisplayP3Color);

$json = json_encode(
    ['brand' => $source->toCss()],
    JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES,
);

echo $json.PHP_EOL;
use PhpColor\Color\Color; use PhpColor\Color\DisplayP3Color; $source = Color::parse( 'color(display-p3 0.925 0.204 0.137 / 0.8)', ); assert($source instanceof DisplayP3Color); $json = json_encode( ['brand' => $source->toCss()], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES, ); echo $json.PHP_EOL;

Restore the stored token

Decode the stored record, parse its CSS value, and compare the restored type and coordinates with the source object.

Continue with the $json and $source variables from the first step:

$record = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
$restored = Color::parse($record['brand']);

assert($restored instanceof DisplayP3Color);
assert($restored->getChannels() === $source->getChannels());
assert($restored->getAlpha() === $source->getAlpha());
assert($restored->toCss() === $record['brand']);
$record = json_decode($json, true, flags: JSON_THROW_ON_ERROR); $restored = Color::parse($record['brand']); assert($restored instanceof DisplayP3Color); assert($restored->getChannels() === $source->getChannels()); assert($restored->getAlpha() === $source->getAlpha()); assert($restored->toCss() === $record['brand']);

Verify the stored representation

The serialized record contains the Display P3 function rather than a converted hexadecimal value:

{"brand":"color(display-p3 0.925 0.204 0.137 / 0.8)"}
{"brand":"color(display-p3 0.925 0.204 0.137 / 0.8)"}

Use a different storage schema if your application needs provenance or original authoring notation. PHPColor exposes the parsed color space, not the exact spelling of the original input.

Related pages