marando/color

PHP class to represent and convert colors.

1.3 2017-02-20 05:18 UTC

This package is not auto-updated.

Last update: 2024-05-16 08:23:47 UTC


README

PHP class to represent and convert colors

Installation

composer require marando/color

Usage/Examples

Import

use Marando/Color/Color;

Creating a Color

Parse

A hsl, rgb or hex HTML string representing a color can be parsed:

Color::parse('hsl(90,90%,50%)');  // #17d98f
Color::parse('rgb(23,217,143)');  // #80f20d
Color::parse('c9189d');           // #c9189d

From RGB

$color = Color::rgb(0, 255, 0);

Note: RGB values can range from 0 to 255.

From HSL

$color = Color::hsl(180, 0.5, 0.5);

Note: Hue can range from 0 to 360, saturation and luminance 0 to 1.

From Hex

$color = Color::hex('#f80');
$color = Color::hex('#7c60e2');

Note: Both three and six digit hex codes are supported.

Conversions

To RGB

$color = Color::hsl(180, 0.5, 0.5);

$color->r;  // 64
$color->g;  // 191
$color->b;  // 191

To get an array of the above:

$color->rgb;  // [64, 191, 191]

To HSL

$color = Color::rgb(0, 255, 0);

$color->h;  // 120
$color->s;  // 1
$color->l;  // 0.5

To get an array of the above:

$color->hsl;  // [120, 1, 0.5]

To Hex

$color = Color::hsl(180, 50, 50);

$color->hex;  // #40bfbf

Miscellaneous

Color Distance

This can be used to compare distances between colors. In the example below the color amethyst is "closer" to white than it is black. This is useful for determining appropriate contrast colors.

$black = Color::hex('#000');
$white = Color::hex('#fff');

$amethyst = Color::hex('#9668c2');

$amethyst->dist($black);  // 266.36816626617
$amethyst->dist($white);  // 193.77048278827

Random Colors

A random color can be generated by using the rand() static constructor:

Color::rand();  // #c42c11

You can limit the range of the random color by specifying a range of HSL values:

for ($i = 0; $i < 10; $i++)
  Color::rand([10, 20], [0.3, 0.4], [0.8, 0.9]);

Notice how the hue, saturation, and luminance stay within the defined ranges:

#ebd7d2 = hsl(12, 0.38, 0.87)
#e4d0c8 = hsl(17, 0.34, 0.84)
#e7d3ce = hsl(12, 0.34, 0.86)
#e0c3b9 = hsl(15, 0.39, 0.80)
#e5d0ca = hsl(13, 0.34, 0.85)
#e5cfc4 = hsl(20, 0.39, 0.83)
#eedfdc = hsl(10, 0.35, 0.90)
#e9d7d0 = hsl(17, 0.36, 0.86)
#ebdad2 = hsl(19, 0.38, 0.87)
#e1cbc3 = hsl(16, 0.33, 0.82)