Download the PHP package tomloprod/colority without Composer
On this page you can find all versions of the php package tomloprod/colority. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download tomloprod/colority
More information about tomloprod/colority
Files in tomloprod/colority
Package colority
Short Description Colority is a lightweight PHP library designed to handle color transformations, validations and manipulations with ease.
License MIT
Informations about the package colority
Color Engine for PHP
About Colority
Colority is a PHP library for working with colors. It handles conversions between RGB, HSL, Hex, and OKLCH formats, calculates WCAG-compliant contrast ratios, extracts color palettes from images, and more.
Features
Getting Started
-
Instantiating Color Objects
- Create RGB, HSL, Hex, and OKLCH color objects from strings or arrays
- Auto-detect color format with
parse()method
-
Contrast Ratio (WCAG 2.0)
- getBestForegroundColor: Pick the best color from a list of candidates
- getMatchingForegroundColor: Generate a foreground color that matches the background's hue
- getContrastRatio: Calculate contrast ratios between colors
- ContrastRatioScore Enum: Validate accessibility compliance
-
Color Validation
- Parse and validate color strings with type-specific parsers
-
Color Conversion
- Convert between RGB, HSL, Hexadecimal, and OKLCH formats
- Semantic Palette
- Eight built-in semantic slots (primary, secondary, success, danger, warning, info, light, dark) with overrides per slot, in bulk, or by custom name
Color Utilities
- Color Adjustments: Adjust brightness and saturation
- getImageMostCommonColor: Get the single most common color in an image
- getImageColors: Extract representative colors from images using K-Means clustering
- getImageDominantColors: Extract dominant colors by pixel frequency with metadata
- textToColor: Generate deterministic colors from strings (usernames, emails, etc.)
- getSimilarColor: Get random colors in the same palette
- random: Generate completely random colors
- gradient: Create smooth color gradients between multiple colors
Using Colority
- Ways of using Colority
- Helper function
colority()and facade pattern
- Helper function
Documentation & Resources
- API Reference: Complete documentation of all classes and methods
- Installation and Requirements: Get started with Composer
Getting Started
Instantiating Color objects
You can convert value colors (strings or, additionally, depending on the color type, arrays) to specific Color objects.
Separator flexibility: RGB, HSL and OKLCH accept commas, whitespace or any combination as component separators (CSS Color Module Level 4). The internal canonical form remains stable: RGB and HSL store with commas, OKLCH stores with whitespace.
If you cannot specify the original format of the value color, use the parse() method. It will auto-detect the color type and return the appropriate Color object, or null if the format is invalid.
Gradients
parse() accepts CSS gradient strings and returns the dominant single color of the gradient, the stop whose visual area along the gradient axis is the largest.
Supported syntax:
linear-gradient(...),radial-gradient(...),conic-gradient(...).- Any combination of CSS-supported color formats inside the stops (hex, rgb, hsl, oklch).
- Optional
<position>%after each stop. Missing positions are filled in following CSS rules: first stop defaults to0%, last stop defaults to100%, intermediate gaps are evenly distributed between declared neighbors. - Trailing
!importantis stripped before parsing. - Metadata segments (angle like
135deg, shape likecircle, position likefrom 90deg at 50% 50%) are detected and skipped.
Dominance rule: for each stop the dominance interval is bounded by the midpoints with its neighbors (clamped to [0, 100] at the ends). The stop with the widest interval wins. Ties resolve to the first stop in declaration order.
Limitations:
- Named CSS colors (
red,blue, etc.) are not supported as stops; use hex/rgb/hsl/oklch. - The library returns one of the original stops, not a perceptual average. If every stop fails to parse,
parse()returnsnull.
Contrast ratio (WCAG 2.0 standard)
When you have the Color object, you will be able to use all its methods. Below, we describe two of them related to the contrast ratio.
getBestForegroundColor
Returns a Color object with the most suitable foreground color (using the Luminosity Contrast Ratio algorithm).
You can pass an array with Color objects as a parameter, so it chooses the foreground color with the best contrast ratio. If no parameter is specified, it will default to white or black.
getContrastRatio
Returns the contrast ratio (higher is better contrast, lower is worse) between the color invoking this method and the color passed as a parameter. If no color is passed as a parameter, the contrast ratio against black as foreground will be determined.
Contrast ratio scale:
- 1.0: No contrast (same color)
- 3.0: Minimum for UI components (WCAG AA)
- 4.5: Minimum for normal text (WCAG AA)
- 7.0: Enhanced contrast for normal text (WCAG AAA)
- 21.0: Maximum contrast (black on white)
getMatchingForegroundColor
Generates a foreground color that preserves the background's hue while meeting WCAG contrast requirements.
Difference from
getBestForegroundColor:
getBestForegroundColor()picks the best color from a list of candidates (defaults to black/white)getMatchingForegroundColor()generates a new color by adjusting lightness while keeping the same hue
Optional parameters:
targetScore(default: ContrastRatioScore::Excellent): The desired contrast level. See ContrastRatioScore Enum.lightnessStep(default: 1): The amount of lightness points (1-100) to jump in each iteration while searching for a matching color. Larger values are faster but less precise.
ContrastRatioScore Enum
The Tomloprod\Colority\Support\Algorithms\ContrastRatioScore enum defines the standard contrast levels and provides helper methods to validate them.
Available contrast levels:
ContrastRatioScore::Excellent(default): 7:1 ratio (WCAG AAA for normal text)ContrastRatioScore::Good: 4.5:1 ratio (WCAG AA for normal text)ContrastRatioScore::Acceptable: 3:1 ratio (WCAG AA for large text/UI).ContrastRatioScore::Insufficient
You can also use the enum's static methods to manually check if a specific contrast ratio meets WCAG levels:
Color validation
The concrete Color classes have a static method called getParser() which returns an instance of ValueColorParser.
The parse method returns a string with the value color adapted to work correctly with Colority or throws an InvalidArgumentException when it's not valid.
You can use the specific parser for any type of color:
Color conversion
Colority allows you to convert a Color object to any other Color object of the desired format.
Note: Conversions between RGB, HSL, and Hex are lossless. Conversions involving OKLCH may be lossy (due to gamut clipping-OKLCH can represent colors outside the sRGB gamut that must be clipped to the nearest displayable color).
CSS-ready string with measure units
HslColor and OklchColor implement the HasMeasureUnits interface, which exposes a string with the conventional unit suffixes for the format.
For OKLCH, L is rendered as a percentage of 1, C as a percentage of the 0.4 reference (so 0.1 becomes 25%), and H with the deg suffix.
Semantic palette
Colority ships with eight semantic color slots primary, secondary, success, danger, warning, info, light, dark, preloaded with default values and overridable per slot, in bulk, or all at once.
Override individual slots
Each slot has a dedicated setter. Both Color instances and hex strings are accepted.
Bulk configuration
configure() overrides multiple slots at once and preserves the ones not provided.
Custom slot names
Beyond the eight semantic names, you can register and read arbitrary slots through the generic accessors.
Reverting to defaults
resetPalette() discards every override and restores the eight defaults. Useful between tests.
The eight defaults Colority ships with:
| Slot | Hex |
|---|---|
primary |
#5B8DEF |
secondary |
#A1A8B3 |
success |
#4BD396 |
danger |
#F5707A |
warning |
#F9C851 |
info |
#3AC9D6 |
light |
#F4F6F8 |
dark |
#1F2937 |
Build a palette from a brand color
buildPalette() derives a coherent palette from a single brand color. The algorithm, applied in HSL space:
| Slot | Formula |
|---|---|
primary |
the brand color, untouched |
secondary |
HSL(brand.H + 180°, max(10, brand.S × 0.4), brand.L), complementary hue with saturation reduced to 40% (floored at 10 so it never goes pure grey). When the brand itself is near-grey (S < 5), the default secondary is used instead. |
light |
brand.lighter(40), lightness + 40 (clamped to 100) |
dark |
brand.darker(40), lightness - 40 (clamped to 0) |
The semantic slots (success, danger, warning, info) keep their library defaults so they remain visually recognizable across brands. Any custom slots previously registered via setColor() are dropped, buildPalette() rebuilds the whole palette.
Color utilities
Color Adjustments
Adjust the brightness (lightness) and saturation of any color. All methods return an HslColor that you can convert as needed.
getImageMostCommonColor
Returns the single most common color in an image based on pixel frequency.
getImageColors
It allows you to obtain the colors detected in an image. As the first argument, the path to the image must be provided.
It has an optional second parameter (default is 5) that specifies the number of colors to be returned.
getImageDominantColors
Extracts the most dominant colors based on pixel frequency, returning detailed metadata for each color.
Optional parameter:
similarityThreshold(default: 50): Minimum RGB distance (0-441) to consider colors as distinct. Higher values filter out more similar colors.
textToColor
Generate a deterministic color based on any string. Same input always produces the same color.
Constrain to a color range:
Pass a fromColor to generate only colors within the same hue range.
Interpolate between two colors:
Pass both fromColor and toColor to perform linear interpolation. The same text always maps to the same position in the gradient.
getSimilarColor
Generate a random color similar to a given color (within the same color palette).
random
Generates a completely random color.
gradient
Generates a smooth gradient of colors between multiple color stops.
This returns an array of 10 HexColor objects.
Ways of using Colority
You can use Colority either with the helper function colority():
or by directly invoking the static methods of the Colority facade:
Both approaches are equivalent.
API Reference
Colority provides a comprehensive API through its facade and color classes.
View complete API documentation
Installation and Requirements
Requires PHP 8.2+
You may use Composer to install Colority into your PHP project:
Upgrade from 1.x to 2.0
Most consumers (those using colority() or the Colority facade) do not need to change anything. The breaking changes affect only callers who reach into the internal parser API:
Tomloprod\Colority\Contracts\ValueColorParser::parse()now returnsarray<ColorComponent>instead ofstring. Direct callers must adapt to the new return shape.ColorityManager::fromHex()andColority::fromHex()acceptstring|array<int|float>. Existing string usage is unchanged; the array form is additive.colority()->parse()now intercepts CSS gradient strings and returns the dominant stop color. Code that relied onparse()returningnullfor gradients should use theGradientResolver::isGradient()static check.getMatchingForegroundColor()defaultstargetScoretoContrastRatioScore::Excellent(7:1, WCAG AAA) instead ofContrastRatioScore::Good(4.5:1, WCAG AA). Pass the enum explicitly to opt back into the previous default.
Contributing
Contributions are welcome, and are accepted via pull requests. Please review these guidelines before submitting any pull requests.
Colority was created by Tomás López and open-sourced under the MIT license.
All versions of colority with dependencies
ext-mbstring Version *