PHP Classes

How to Use a PHP Color Change Class to Manipulate Colors using the Package Colority: Perform color transformation operations

Recommend this page to a friend!
  Info   View files Documentation   View files View files (39)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-05-25 (22 days ago) RSS 2.0 feedNot yet rated by the usersTotal: 31 All time: 11,046 This week: 46Up
Version License PHP version Categories
colority 1.0.0Custom (specified...8.2Algorithms, Graphics, Validation, Par..., P...
Description 

Author

This package can perform color transformation operations.

It provides a class that can perform operations on colors provided as strings in several formats like RGB, hexadecimal, and HSL.

Currently, it can perform the following color operations:

- Can extract colors from images

- Change the color luminosity

- Change the color contrast

- Return the color in different formats

- Generate similar colors (same color palette) to a given color

- Generate a unique color from a string (e.g., a username)

- Check the contrast ratio to see if it meets the WCAG 2.0 standard

Picture of tomloprod
  Performance   Level  
Name: tomloprod <contact>
Classes: 3 packages by
Country: Spain Spain

Instructions

Ways of using Colority

You can use Colority with the helper colority() or with the facade:

/ @var HexColor $hexColor */
$hexColor = colority()->fromHex('#CCC');

or

/ @var HexColor $hexColor */
$hexColor = Colority::fromHex('#CCC');

Extract colors from images

/ @var array<RgbColor> $imageColors */
$imageColors = colority()->getImageColors(
    imagePath: __DIR__.'/image-colors.png',
    desiredNumColors: 10
);

Generate color from string

/ @var HslColor $hslColor */
$hslColor = colority()->textToColor("Hi, I'm Tomás");

Determine the text color (white, black, or others) based on the background color

/ @var HexColor $hexColor */
$hexColor = colority()->fromHex('#51B389');

/ @var HexColor $bestForegroundHexColor (black or white) */
$bestForegroundHexColor = $hexColor->getBestForegroundColor();

/ @var HexColor $bestForegroundHexColor (#A63F3F, #3FA684 or #6E3FA6) */
$bestForegroundHexColor = $hexColor->getBestForegroundColor([
    new HexColor('#A63F3F'),
    new HexColor('#3FA684'),
    new HexColor('#6E3FA6'),
]);

Check if the contrast ratio meets the WCAG 2.0 accessibility standard for people with vision impairments.


/ @var HexColor $hexColor */
$hexColor = colority()->fromHex('#51B389');

/
 * The `getContrastRatio` method can take a `Color` object as the foreground 
 * to calculate the contrast ratio against that color. Black is used by default.
 * 
 * @var float $contrastRatio
 */
$contrastRatio = $hexColor->getContrastRatio();

/
 * AA Level for texts
 */
$passsesAALevelForLargeText = ContrastRatioScore::passesTextAALevel(
    contrastRatio: $contrastRatio,
    largeText: true
);

$passsesAALevelForNormalText = ContrastRatioScore::passesTextAALevel(
    contrastRatio: $contrastRatio,
    largeText: false
);

/
 * AAA Level for texts
 */
$passsesAAALevelForLargeText = ContrastRatioScore::passesTextAAALevel(
    contrastRatio: $contrastRatio,
    largeText: true
);

$passsesAAALevelForNormalText = ContrastRatioScore::passesTextAAALevel(
    contrastRatio: $contrastRatio,
    largeText: false
);
/
 * AA Level for Graphical Objects and User Interface Components
 */
$passsesAALevelForUI = ContrastRatioScore::passesUIAALevel(
    $contrastRatio
);

Color conversion

/ @var HexColor|null $hexColor */
$hexColor = colority()->fromHex('#51B389');

/ @var HexColor $hexColor */
$hexColor = $hexColor->toHex();

/ @var RgbColor $rgbColor */
$rgbColor = $hexColor->toRgb();

/ @var HslColor $hslColor */
$hslColor = $hexColor->toHsl();

All the details

For all the details, refer to the README.md where you can also find some GIFs to visually see how Colority works.

Documentation

<p align="center">

<img title="Laravel Zero" height="100" src="./docs/colority.png" alt="Colority" />

</p>

<p align="center">

<p align="center">
    <a href="https://github.com/tomloprod/colority/actions"><img alt="GitHub Workflow Status (master)" src="https://github.com/tomloprod/colority/actions/workflows/tests.yml/badge.svg"></a>
    <a href="https://packagist.org/packages/tomloprod/colority"><img alt="Total Downloads" src="https://img.shields.io/packagist/dt/tomloprod/colority"></a>
    <a href="https://packagist.org/packages/tomloprod/colority"><img alt="Latest Version" src="https://img.shields.io/packagist/v/tomloprod/colority"></a>
    <a href="https://packagist.org/packages/tomloprod/colority"><img alt="License" src="https://img.shields.io/packagist/l/tomloprod/colority"></a>
</p>

</p>

? About Colority

Colority is a lightweight PHP library designed to handle color transformations, validations and manipulations with ease.

It allows you to instantiate concrete objects according to the color format (RGB, HSL, Hexadecimal) and convert from one format to another.

Additionally, it lets you check if a background color meets the WCAG 2.0 accessibility standard regarding the color contrast ratio in text and UI.

Furthermore, it includes multiple functions such as the following:

  • Generate the best foreground color (white, black, or from a user-provided list) for a background color, ensuring the best possible contrast ratio. (important for improving text visibility on, for example, colored badges).
  • Generate a fixed color based on a string. Useful for generating a color associated with, for example, a username.
  • Allows you to obtain a random color similar to a given color.

? Getting Started

Instantiating Color objects

You can convert value colors (strings or, additionally, depending on the color type, arrays) to specific Color objects.

/ @var RgbColor $rgbColor */
$rgbColor = colority()->fromRgb('rgb(255,255,255)');
$rgbColor = colority()->fromRgb('255,255,255'); 
$rgbColor = colority()->fromRgb([255, 255, 255]); 

/ @var HexColor $hexColor */
$hexColor = colority()->fromHex('#51B389');
$hexColor = colority()->fromHex('51B389'); 
$hexColor = colority()->fromHex('#ABC');

/ @var HslColor $hslColor */
$hslColor = colority()->fromRgb('hsl(168.31deg, 49.58%, 46.67%)');
$hslColor = colority()->fromRgb('168.31, 49.58, 46.67'); 
$hslColor = colority()->fromRgb([168.31, 49.58, 46.67]); 

If you cannot specify the original format of the value color, you can use the parse method. This will detect what type of color it is and instantiate a new object or, if the received string does not match any type of color, it will return NULL:

/ @var RgbColor|null $rgbColor */
$rgbColor = colority()->parse('rgb(255,255,255)');

/ @var HexColor|null $hexColor */
$hexColor = colority()->parse('#51B389');

/ @var HslColor|null $hslColor */
$hslColor = colority()->parse('hsl(168.31deg, 49.58%, 46.67%)');

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.

/ @var HexColor $hexColor */
$hexColor = colority()->fromHex('#51B389');

/ @var HexColor $bestForegroundHexColor (black or white) */
$bestForegroundHexColor = $hexColor->getBestForegroundColor();

/ @var HexColor $bestForegroundHexColor (#A63F3F, #3FA684 or #6E3FA6) */
$bestForegroundHexColor = $hexColor->getBestForegroundColor([
    new HexColor('#A63F3F'),
    new HexColor('#3FA684'),
    new HexColor('#6E3FA6'),
]);

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.

/ @var HexColor $hexColor */
$hexColor = colority()->fromHex('#51B389');

/ @var float $contrastRatio Contrast ratio with black as the foreground color. */
$contrastRatio = $hexColor->getContrastRatio();

/ @var float $contrastRatio Contrast ratio with #3FA684 as the foreground color. */
$contrastRatio = $hexColor->getContrastRatio(new HexColor('#3FA684'));

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.

/ @var ValueColorParser $hexParser */
$hexParser = HexColor::getParser();

// will throw InvalidArgumentException
$valueColor = $hexParser->parse('Not a valid value color'); 

// will return #FFFFFF
$valueColor = $hexParser->parse('#FFF');

You can use the specific parser for any type of color:

$hslParser = HslColor::getParser();

$rgbParser = RgbColor::getParser();

$hexParser = HexColor::getParser();

Color conversion

Colority allows you to convert a Color object to any other Color object of the desired format.

/ @var HexColor|null $hexColor */
$hexColor = colority()->fromHex('#51B389');

/ @var HexColor $hexColor */
$hexColor = $hexColor->toHex();

/ @var RgbColor $rgbColor */
$rgbColor = $hexColor->toRgb();

/ @var HslColor $hslColor */
$hslColor = $hexColor->toHsl();

Color utilities

textToColor

Generate a fixed color based on a string.

/ @var HslColor $hslColor */
$hslColor = colority()->textToColor("Hi, I'm Tomás");

> ? Advise > Useful for generating a color associated with, for example, a username, mail address, etc, since a string will always return the same color.

getSimilarColor

Allows you to obtain a random color similar (in the same color palette) to a given color.

/ @var HexColor|null $hexColor */
$hexColor = colority()->fromHex('#51B389');

/ @var HexColor|null $similarHexColor */
$similarHexColor = colority()->getSimilarColor($hexColor);

Ways of using Colority

You can use Colority either with the aliases colority()

/ @var HexColor $hexColor */
$hexColor = colority()->fromHex('#CCC');

or by directly invoking the static methods of the Colority facade:

/ @var HexColor $hexColor */
$hexColor = Colority::fromHex('#CCC');

You decide how to use it ?

? Architecture

Colority is composed of several types of elements. Below are some features of each of these elements.

Colority

Tomloprod\Colority\Support\Facades\Colority is a facade that acts as a simplified interface for using the rest of the Colority elements.

Methods


Colority::parse(string $valueColor): Color|null

Colority::fromHex(string $hexValue): HexColor

Colority::fromRgb(string|array<int> $rgbValue): RgbColor

Colority::fromHsl(string|array<float> $hslValue): HslColor

Colority::textToColor(string $text): HslColor

Colority::getSimilarColor(Color $color, int $hueRange = 30, int $saturationRange = 10, int $lightnessRange = 10): Color

Color

All concrete color classes extend the abstract class Color. Concrete color classes: - Tomloprod\Colority\Colors\HexColor - Tomloprod\Colority\Colors\HslColor - Tomloprod\Colority\Colors\RgbColor

Methods

/ @var HexColor $hexColor */
$hexColor = Colority::fromHex('#CCCCCC');

$hexColor->toHex(): HexColor;
$hexColor->toRgb(): RgbColor;
$hexColor->toHsl(): HslColor;

// Returns the value color in string format. Example: #CCCCCC
$hexColor->getValueColor(): string;

For the HslColor and RgbColor objects, you also have a method getArrayValueColor that will return the value color in array format:

/ @var RgbColor $rgbColor */
$rgbColor = Colority::fromRgb('255,255,255');

/ @var array $arrayValueColor [255,255,255] */
$arrayValueColor = $rgbColor->getArrayValueColor();

On the other hand, the HslColor object has an additional method called getValueColorWithMeasureUnits, which returns the value color, but with units of measurement (useful for, for example, using it in a CSS style):

/ @var HslColor $hslColor */
$hslColor = Colority::fromHsl('hsl(32.4, 60.48, 51.37)');

/ @var string $valueColorWithMeasureUnits hsl(32.4deg,60.48%,51.37%) */
$valueColorWithMeasureUnits = $hslColor->getValueColorWithMeasureUnits();

/ @var string $valueColor hsl(32.4,60.48,51.37) */
$valueColor = $hslColor->getValueColor(): string;

? Installation & Requirements

> Requires PHP 8.2+

You may use Composer to install Colority into your PHP project:

composer require tomloprod/colority

????? 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.


  Files folder image Files  
File Role Description
Files folder image.github (1 file, 1 directory)
Files folder imagedocs (1 file)
Files folder imagesrc (5 directories)
Files folder imagetests (1 file, 4 directories)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file CHANGELOG.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file CONTRIBUTING.md Data Auxiliary data
Accessible without login Plain text file LICENSE.md Lic. License text
Accessible without login Plain text file phpstan.neon.dist Data Auxiliary data
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file pint.json Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation
Plain text file rector.php Class Class source

  Files folder image Files  /  .github  
File Role Description
Files folder imageworkflows (2 files)
  Accessible without login Plain text file FUNDING.yml Data Auxiliary data

  Files folder image Files  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file formats.yml Data Auxiliary data
  Accessible without login Plain text file tests.yml Data Auxiliary data

  Files folder image Files  /  docs  
File Role Description
  Accessible without login Image file colority.png Icon Icon image

  Files folder image Files  /  src  
File Role Description
Files folder imageColors (4 files)
Files folder imageConcerns (1 file)
Files folder imageContracts (2 files)
Files folder imageServices (1 file)
Files folder imageSupport (2 files, 3 directories)

  Files folder image Files  /  src  /  Colors  
File Role Description
  Plain text file Color.php Class Class source
  Plain text file HexColor.php Class Class source
  Plain text file HslColor.php Class Class source
  Plain text file RgbColor.php Class Class source

  Files folder image Files  /  src  /  Concerns  
File Role Description
  Plain text file ResolvesContrastRatioColor.php Class Class source

  Files folder image Files  /  src  /  Contracts  
File Role Description
  Plain text file TransformableColor.php Class Class source
  Plain text file ValueColorParser.php Class Class source

  Files folder image Files  /  src  /  Services  
File Role Description
  Plain text file ColorityManager.php Class Class source

  Files folder image Files  /  src  /  Support  
File Role Description
Files folder imageAlgorithms (2 files)
Files folder imageFacades (1 file)
Files folder imageParsers (3 files)
  Accessible without login Plain text file ColorityAlias.php Aux. Auxiliary script
  Plain text file ValueColorParserResolver.php Class Class source

  Files folder image Files  /  src  /  Support  /  Algorithms  
File Role Description
  Accessible without login Plain text file ContrastRatioScore.php Example Example script
  Plain text file LuminosityContrastRatio.php Class Class source

  Files folder image Files  /  src  /  Support  /  Facades  
File Role Description
  Plain text file Colority.php Class Class source

  Files folder image Files  /  src  /  Support  /  Parsers  
File Role Description
  Plain text file HexValueColorParser.php Class Class source
  Plain text file HslValueColorParser.php Class Class source
  Plain text file RgbValueColorParser.php Class Class source

  Files folder image Files  /  tests  
File Role Description
Files folder imageColors (3 files)
Files folder imageConcerns (1 file)
Files folder imageServices (1 file)
Files folder imageSupport (1 file, 2 directories)
  Accessible without login Plain text file ArchTest.php Example Example script

  Files folder image Files  /  tests  /  Colors  
File Role Description
  Plain text file HexColorTest.php Class Class source
  Plain text file HslColorTest.php Class Class source
  Plain text file RgbColorTest.php Class Class source

  Files folder image Files  /  tests  /  Concerns  
File Role Description
  Accessible without login Plain text file ResolvesContrastRatioColorTest.php Example Example script

  Files folder image Files  /  tests  /  Services  
File Role Description
  Plain text file ColorityManagerTest.php Class Class source

  Files folder image Files  /  tests  /  Support  
File Role Description
Files folder imageAlgorithms (1 file)
Files folder imageFacades (1 file)
  Plain text file ColorityAliasTest.php Class Class source

  Files folder image Files  /  tests  /  Support  /  Algorithms  
File Role Description
  Accessible without login Plain text file LuminosityContrastRatioTest.php Example Example script

  Files folder image Files  /  tests  /  Support  /  Facades  
File Role Description
  Accessible without login Plain text file ColorityTest.php Example Example script

 Version Control Unique User Downloads Download Rankings  
 100%
Total:31
This week:0
All time:11,046
This week:46Up