tc-lib-color

Technical guide for integrating tc-lib-color: color parsing, conversion, and PDF/web output

Overview

tc-lib-color provides parsing, conversion, and formatting of color values for web and PDF rendering pipelines.

One normalization layer covers RGB, CMYK, HSL, grayscale, Lab, and spot colors, in both their CSS and their PDF representations. Conversions written ad hoc in three places tend to round differently in all three; here they do not.

Repository and API Docs

Project Metadata

ItemValue
Namespace\Com\Tecnick\Color
LicenseGNU LGPL v3

Installation

composer require tecnickcom/tc-lib-color

Where It Fits

Use this package whenever rendering needs explicit color conversions and repeatable output across digital and print contexts. It is a direct dependency of tecnickcom/tc-lib-pdf and is used internally for all color operations during PDF composition.

Color Models

ModelClass
RGB / RGBA\Com\Tecnick\Color\Model\Rgb
HSL / HSLA\Com\Tecnick\Color\Model\Hsl
CMYK\Com\Tecnick\Color\Model\Cmyk
CIE Lab\Com\Tecnick\Color\Model\Lab
Grayscale\Com\Tecnick\Color\Model\Gray

Each page gives the components, the ranges and the output of every accessor; Colour Models puts the five side by side and Conversions covers moving between them.

Spot colors (Separation) are handled by \Com\Tecnick\Color\Spot, with DeviceCMYK and Lab alternate color spaces for PDF output.

Integration Helpers

  • CSS output that parses back to the same color
  • PDF and Acrobat JavaScript color output
  • Cross-model conversion helpers on all color models
  • Named web color lookup (CSS Color Module Level 4 names) and nearest-color matching in sRGB or CIE Lab

Main Classes

ClassPurpose
\Com\Tecnick\Color\WebNamed web colors, hex parsing, nearest-color lookup
\Com\Tecnick\Color\PdfPDF color operators, spot color objects, JS color strings
\Com\Tecnick\Color\CssCSS color string parsing and normalization
\Com\Tecnick\Color\SpotSpot color registry and PDF spot color resource generation
\Com\Tecnick\Color\ComponentNormalizerScaling of parsed component values into the [0..1] range

Pdf extends Spot extends Web extends Css, so a single object provides the parser, the spot registry and the PDF writer. Each role also has its own interface to type against:

InterfaceRole
\Com\Tecnick\Color\ColorParserInterfaceColor string parsing and named color lookup
\Com\Tecnick\Color\SpotRegistryInterfaceSpot color registration and PDF spot resource output
\Com\Tecnick\Color\PdfColorWriterInterfacePDF and Acrobat JavaScript color output
\Com\Tecnick\Color\ExceptionInterfaceCommon interface of the library exceptions

Web::getColorObj(), Spot::getSpotColor(), Pdf::getPdfColor() and Pdf::getColorObject() can be overridden, along with the protected parser methods on Css and Spot::resolveSpotColorData(). Every other public method is final.

Supported Color Notations

getColorObj() accepts hexadecimal codes in four lengths, the 150 named colors, seven color functions (g(), rgb(), rgba(), hsl(), hsla(), cmyk(), cmyka(), lab()) and the Acrobat JavaScript array forms. Components are separated either by commas or by spaces, not by a mixture of the two; out-of-range components are clamped and hues wrap, as CSS Color Level 4 requires.

Colour Notations has every form with its parsed result, the angle units, the alpha syntax and what transparent resolves to.

Typed Enums

\Com\Tecnick\Color\ColorModelType is a backed enum listing the supported color models (GRAY, RGB, HSL, CMYK, LAB). Its backing value is the canonical model string returned by the model objects, so it can be used interchangeably with the plain string wherever a model type is accepted. Model::create() builds a model object from an enum case and a component array.

Exceptions

\Com\Tecnick\Color\Exception (a \Exception) signals invalid input. \Com\Tecnick\Color\UnknownComponentException (a \LogicException) signals a component name a model does not define, and is not swallowed by the lenient accessors tryGetColorObj() and getColorObject(). Both implement \Com\Tecnick\Color\ExceptionInterface, so a single catch covers them.

Errors lists every message with the call that raises it, and the inputs that clamp instead of raising.

Version 3.0 Changes

Release 3.0 is a breaking change:

  • Rgb::getCssColor() emits rgb(255,0,0) and Gray::getCssColor() emits g(128) instead of percentage forms; alpha is capped at four decimals.
  • The PDF color getters take a trailing bool $allowSpot = true argument, and most public methods of Web, Spot and Pdf are final.
  • Model::__construct() is removed from the abstract base: each model validates its own components and raises UnknownComponentException.
  • Malformed numbers and mixed comma/space separators are rejected; out-of-range components clamp and hues wrap.
  • Css::normalizeValue() is concrete and delegates scaling to the ComponentNormalizer collaborator.
  • New API: the role interfaces, Model::withInvertedColor(), Web::getClosestWebColorByDeltaE(), CSS angle units, slash-alpha and percentage alpha.
  • addSpotLabColor() clamps its range to [-128..127], the spot color accessors return copies, and a spot resource with no PDF object raises instead of being emitted.

How Integration Works

  1. Instantiate Web or Pdf depending on target output context.
  2. Parse input color strings (hex, CSS, named, spot) into a color model object.
  3. Use model output methods to produce CSS strings, PDF operators, or normalized arrays.
  4. For PDF output, use Pdf::getPdfColor() to emit the correct PDF color operator.
<?php

require_once __DIR__ . '/vendor/autoload.php';

$pdf = new \Com\Tecnick\Color\Pdf();

$color = $pdf->getColorObject('#336699');
echo $color->getCssColor();   // rgb(51,102,153)
echo $pdf->getPdfFillColor('#336699');

Pdf extends the spot registry, which extends the web parser, so one object covers every step. The reference pages carry the worked examples:

TaskPage
Write a color string the parser acceptsColour Notations
Pick a model and read its componentsColour Models
Move a color between modelsConversions
Look up or name a colorWeb Colours, Nearest Colour
Register an ink and emit its resourcesSpot Colours
Write color into a PDFPDF Output
Handle bad inputErrors

Behavior Worth Knowing

  • Spot colors are registered only when you add them explicitly. The color getters do not register one as a side effect, so the spot resources a document emits match the ones it actually uses.
  • Spot color names are escaped when written to PDF, and the CSS parser recognizes the standard spot color names.
  • Spot colors take a DeviceCMYK or a Lab alternate color space in PDF output.
  • HSL saturation and lightness are always parsed as percentages, as the CSS specification requires.

Integration Notes

Parse color notation once, at the edge of your application, and pass typed model objects inward. Strings that reach the rendering layer get reparsed, sometimes under different assumptions.

RGB and CMYK cover different gamuts, so a screen preview and a press sheet agree across most of the range and differ at the saturated end. Conversions has the conversion matrix and the round-trip measurements.

Lab is the device-independent option, and it is what ISO 19005 prefers. A DeviceCMYK color in a PDF/A document is only valid when the output intent is a CMYK profile, and tc-lib-pdf reports the mismatch through getWarnings(); see /docs/standards/.

Requirements

  • PHP 8.2 or later
  • Extension: pcre
  • Composer

Development and Packaging

  • QA and local checks: make deps, make help, make qa
  • Coverage report: make qa-coverage
  • Local example server: make server
  • Packaging: make rpm, make deb

Support and Contribution