Skip to content

Instantly share code, notes, and snippets.

@rowanmanning
Created June 4, 2010 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rowanmanning/425464 to your computer and use it in GitHub Desktop.
Save rowanmanning/425464 to your computer and use it in GitHub Desktop.
A simple colour class for PHP
<?php
//============================================================
// DEPENDENCIES
//============================================================
// include the colour class
include 'Graphics_Color.php';
//============================================================
?>
<!DOCTYPE html>
<html lang="en-gb">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="description" content="Page description"/>
<meta name="keywords" content="page keywords"/>
<link rel="stylesheet" type="text/css" href="http://github.com/rowanmanning/terf/raw/master/terf/css/core.css"/>
<style type="text/css">
body {
padding: 20px;
}
</style>
<title>PHPColor Examples</title>
</head>
<body>
<h1>PHPColor Examples</h1>
<hr/>
<h3>Create a Color object</h3>
<h5>Code</h5>
<pre><code>$c = new Graphics_Color(255, 0, 0);</code></pre>
<hr/>
<h3>Get a colour's HEX code</h3>
<h5>Code</h5>
<pre><code>$c = new Graphics_Color(255, 0, 0);
print $c->get_hex();
print '&lt;br/&gt;';
print $c->get_hex(true);</code></pre>
<h5>Output</h5>
<p><?php
$c = new Graphics_Color(255, 0, 0);
print $c->get_hex();
print '<br/>';
print $c->get_hex(true);
?></p>
<hr/>
<h3>Create a Color object using a HEX code</h3>
<h5>Code</h5>
<pre><code>$c = new Graphics_Color();
$c->set_hex('#ff0000') // accepts 3-character or 6-character variants</code></pre>
<hr/>
<h3>Mix two colours</h3>
<h5>Code</h5>
<pre><code>$c1 = new Graphics_Color(255, 0, 0);
$c2 = new Graphics_Color(0, 0, 204);
$c3 = Graphics_Color::mix($c1, $c2);
print $c3->get_hex(true);</code></pre>
<h5>Output</h5>
<p><?php
$c1 = new Graphics_Color(255, 0, 0);
$c2 = new Graphics_Color(0, 0, 204);
$c3 = Graphics_Color::mix($c1, $c2);
print $c3->get_hex(true);
?></p>
<h5>Visual</h5>
<p>
<span style="color:<?php print $c1->hex; ?>;">Colour 1</span>
mixed with
<span style="color:<?php print $c2->hex; ?>;">Colour 2</span>
makes
<span style="color:<?php print $c3->hex; ?>;">Colour 3</span>
</p>
<hr/>
<h3>Get a colour range</h3>
<h5>Code</h5>
<pre><code>$c1 = new Graphics_Color(0, 0, 255);
$c2 = new Graphics_Color(0, 255, 0);
$range = Graphics_Color::range($c1, $c2, 10);
foreach ($range as $cr){
print $cr->get_hex(true);
print ', ';
}</code></pre>
<h5>Output</h5>
<p><?php
$c1 = new Graphics_Color(0, 0, 255);
$c2 = new Graphics_Color(0, 255, 0);
$range = Graphics_Color::range($c1, $c2, 10);
foreach ($range as $cr){
print $cr->get_hex(true);
print ', ';
}
?></p>
<h5>Visual</h5>
<p class="container"><?php
foreach ($range as $cr){
print '<span style="width:20px;height:20px;display:block;float:left;background:' . $cr->hex . ';"></span>';
}
?></p>
</body>
</html>
<?php
/**
* PHP Color Class
*
* An simple colour class for PHP. Note: in documentation the 'colour' spelling is intentional.
*
* @subpackage Graphics
* @author Rowan Manning (http://rowanmanning.co.uk/)
* @copyright Copyright (c) 2011, Rowan Manning
* @license Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* @link https://gist.github.com/425464
* @filesource
*/
//============================================================
// CLASS DEFINITION
//============================================================
/**
* Color Class
*
* This is the base class used in all colour manipulations.
*
* @subpackage Graphics
* @author Rowan Manning (http://rowanmanning.co.uk/)
* @link https://gist.github.com/425464
*/
class Graphics_Color {
//============================================================
// PRIVATE AND PROTECTED VARIABLES
//============================================================
/**
* The red value of the colour.
*
* @access protected
* @var integer
*/
protected $red = 0;
/**
* The green value of the colour.
*
* @access protected
* @var integer
*/
protected $green = 0;
/**
* The blue value of the colour.
*
* @access protected
* @var integer
*/
protected $blue = 0;
//============================================================
// PROTECTED AND PRIVATE STATIC FUNCTIONS
//============================================================
/**
* Fix a colour value (round and keep between 0 and 255).
*
* @access protected
* @static
* @param integer $value The value to fix.
* @return integer Returns the fixed integer.
*/
protected static function fix_rgb_value($value) {
return max(min(round((integer) $value), 255), 0);
}
//============================================================
// PUBLIC STATIC FUNCTIONS
//============================================================
/**
* Convert red, green and blue values to a HEX code.
*
* @access public
* @param $red The red value of the colour (between 0 and 255).
* @param $green The green value of the colour (between 0 and 255).
* @param $blue The blue value of the colour (between 0 and 255).
* @return string Returns the HEX code representing the values given.
*/
public static function rgb_to_hex($red, $green, $blue) {
// convert rgb to hex
$red = str_pad(dechex(self::fix_rgb_value($red)), 2, '0', STR_PAD_LEFT);
$green = str_pad(dechex(self::fix_rgb_value($green)), 2, '0', STR_PAD_LEFT);
$blue = str_pad(dechex(self::fix_rgb_value($blue)), 2, '0', STR_PAD_LEFT);
// concat and return
return $red . $green . $blue;
}
/**
* Convert a HEX code into RGB.
*
* @access public
* @param string $hex The HEX code to convert.
* @return array Returns an associative array of values. The array will have 'red', 'green' and 'blue' keys.
*/
public static function hex_to_rgb($hex) {
// trim the '#' character
$hex = ltrim((string)$hex, '#');
// what kind of code do we have?
if (strlen($hex) == 6) {
// parse 6-character code into array
$hex = array(
'red' => $hex[0] . $hex[1],
'green' => $hex[2] . $hex[3],
'blue' => $hex[4] . $hex[5]
);
}
else if (strlen($hex) == 3) {
// parse 3 character code into array
$hex = array(
'red' => $hex[0] . $hex[0],
'green' => $hex[1] . $hex[1],
'blue' => $hex[2] . $hex[2]
);
}
else {
// invalid code... oops
$hex = array(
'red' => 0,
'green' => 0,
'blue' => 0,
);
}
// set values
$hex['red'] = self::fix_rgb_value(hexdec($hex['red']));
$hex['green'] = self::fix_rgb_value(hexdec($hex['green']));
$hex['blue'] = self::fix_rgb_value(hexdec($hex['blue']));
// we're ok!
return $hex;
}
/**
* Calculate and return a range of colours between a start and end colour.
*
* @access public
* @param Graphics_Color|string $start The start colour. This can be a Graphics_Color object or a HEX code as a string.
* @param Graphics_Color|string $end The end colour. This can be a Graphics_Color object or a HEX code as a string.
* @param integer $steps The number of colours to return (including start and end colours).
* @return array Returns an array of Graphics_Color objects.
*/
public static function range($start, $end, $steps = 10) {
// do we have a start colour?
if (!is_a($start, 'Graphics_Color')) {
$startc = new Graphics_Color;
$startc->set_hex($start);
$start = $startc;
}
// do we have an end colour?
if (!is_a($end, 'Graphics_Color')) {
$endc = new Graphics_Color;
$endc->set_hex($end);
$end = $endc;
}
// minus start and end from the steps
$steps -= 2;
// get the two colours
$start_rgb = $start->get_array();
$end_rgb = $end->get_array();
// amount to increment on each step
if ($start_rgb['red'] <= $end_rgb['red']) {
$red_increment = -($start_rgb['red'] - $end_rgb['red']) / ($steps+1);
}
else {
$red_increment = ($end_rgb['red'] - $start_rgb['red']) / ($steps+1);
}
if ($start_rgb['green'] <= $end_rgb['green']) {
$green_increment = -($start_rgb['green'] - $end_rgb['green']) / ($steps+1);
}
else {
$green_increment = ($end_rgb['green'] - $start_rgb['green']) / ($steps+1);
}
if ($start_rgb['blue'] <= $end_rgb['blue']) {
$blue_increment = -($start_rgb['blue'] - $end_rgb['blue']) / ($steps+1);
}
else {
$blue_increment = ($end_rgb['blue'] - $start_rgb['blue']) / ($steps+1);
}
// add the start colour to the array
$range = array($start);
// get the range
$steps_taken = 0;
while ($steps_taken < $steps) {
$steps_taken++;
$start_rgb['red'] += $red_increment;
$start_rgb['green'] += $green_increment;
$start_rgb['blue'] += $blue_increment;
$range[] = new Graphics_Color($start_rgb['red'], $start_rgb['green'], $start_rgb['blue']);
}
// add the end colour to the array
$range[] = $end;
// return
return $range;
}
/**
* Mix two colours together.
*
* @access public
* @param Graphics_Color|string $color1 The first colour. This can be a Graphics_Color object or a HEX code as a string.
* @param Graphics_Color|string $color2 The second colour. This can be a Graphics_Color object or a HEX code as a string.
* @return Graphics_Color Returns the result of the mix as a new Graphics_Color object.
*/
public static function mix($color1, $color2) {
// do we have a colour 1?
if (!is_a($color1, 'Graphics_Color')) {
$color1c = new Graphics_Color;
$color1c->set_hex($color1);
$color1 = $color1c;
}
// do we have a colour 2?
if (!is_a($color2, 'Graphics_Color')) {
$color2c = new Graphics_Color;
$color2c->set_hex($color2);
$color2 = $color2c;
}
// get arrays of colour values
$rgb1 = $color1->get_array();
$rgb2 = $color2->get_array();
// mix colours into a new colour and return
return new Graphics_Color($rgb1['red'] + $rgb2['red'], $rgb1['green'] + $rgb2['green'], $rgb1['blue'] + $rgb2['blue']);
}
//============================================================
// PUBLIC FUNCTIONS
//============================================================
/**
* Class constructor.
*
* @access public
* @param integer $red [optional] The red value of the colour (between 0 and 255). Default value is 0.
* @param integer $green [optional] The green value of the colour (between 0 and 255). Default value is 0.
* @param integer $blue [optional] The blue value of the colour (between 0 and 255). Default value is 0.
*/
public function __construct($red = 0, $green = 0, $blue = 0) {
// add values
$this->red = self::fix_rgb_value($red);
$this->green = self::fix_rgb_value($green);
$this->blue = self::fix_rgb_value($blue);
}
/**
* Set the colour's red, green and blue values
*
* @access public
* @param integer $red [optional] The red value of the colour (between 0 and 255). Default value is 0.
* @param integer $green [optional] The green value of the colour (between 0 and 255). Default value is 0.
* @param integer $blue [optional] The blue value of the colour (between 0 and 255). Default value is 0.
*/
public function set($red = 0, $green = 0, $blue = 0) {
// add values
$this->red = self::fix_rgb_value($red);
$this->green = self::fix_rgb_value($green);
$this->blue = self::fix_rgb_value($blue);
}
/**
* Modify the colour's red, green and blue values.
*
* @access public
* @param integer $red [optional] The amount to modify the red value of the colour (between -255 and 255). Default value is 0.
* @param integer $green [optional] The amount to modify the green value of the colour (between -255 and 255). Default value is 0.
* @param integer $blue [optional] The amount to modify the blue value of the colour (between -255 and 255). Default value is 0.
*/
public function modify($red = 0, $green = 0, $blue = 0) {
// add values
$this->red = self::fix_rgb_value($this->red + (int)$red);
$this->green = self::fix_rgb_value($this->green + (int)$green);
$this->blue = self::fix_rgb_value($this->blue + (int)$blue);
}
/**
* Randomise red, green and blue values of the colour.
*
* @access public
*/
public function randomise() {
// randomise values
$this->red = mt_rand(0, 255);
$this->green = mt_rand(0, 255);
$this->blue = mt_rand(0, 255);
}
/**
* Set the red, green and blue values of the colour with a HEX code.
*
* @access public
* @param string $hex The HEX code to set. This must be 3 or 6 characters in length and can optionally start with a '#'.
* @return boolean Returns TRUE on success.
*/
public function set_hex($hex) {
// get the rgb values
$rgb = self::hex_to_rgb($hex);
// set values
$this->red = $rgb['red'];
$this->green = $rgb['green'];
$this->blue = $rgb['blue'];
// we're ok!
return true;
}
/**
* Get the red, green and blue values of the colour as an array.
*
* @access public
* @return array Returns an associative array of values. The array will have 'red', 'green' and 'blue' keys.
*/
public function get_array() {
// return the array
return array(
'red' => $this->red,
'green' => $this->green,
'blue' => $this->blue
);
}
/**
* Get the HEX code that represents the colour.
*
* @access public
* @param boolean $hash Whether to prepend the HEX code with a '#' character. Default value is FALSE.
* @return string Returns the HEX code.
*/
public function get_hex($hash = false) {
return ($hash ? '#' : '') . self::rgb_to_hex($this->red, $this->green, $this->blue);
}
//============================================================
// MAGIC METHODS
//============================================================
/**
* get magic method.
*
* @param string $name The name of the variable to get.
* @return mixed Returns the value of the requested variable.
*/
public function __get($name) {
// get variable
switch ($name) {
case 'red': return $this->red; break;
case 'green': return $this->green; break;
case 'blue': return $this->blue; break;
case 'hex': return $this->get_hex(true); break;
case 'rgb': return $this->get_array(); break;
}
// error
$trace = debug_backtrace();
trigger_error('Undefined property: ' . __CLASS__ . '::$' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'] . ',', E_USER_NOTICE);
return null;
}
/**
* set magic method.
*
* @param string $name The name of the variable to set.
* @param mixed $value The value to set the variable to.
*/
public function __set($name, $value) {
// get variable
switch ($name) {
case 'red': $this->red = self::fix_rgb_value($value); return; break;
case 'green': $this->green = self::fix_rgb_value($value); return; break;
case 'blue': $this->blue = self::fix_rgb_value($value); return; break;
case 'hex': $this->set_hex($value); return; break;
}
// error
$trace = debug_backtrace();
trigger_error('Undefined property: ' . __CLASS__ . '::$' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'] . ',', E_USER_NOTICE);
return;
}
/**
* toString magic method.
*
* @return string Returns the HEX code that represents the colour.
*/
public function __toString() {
return $this->get_hex(true);
}
//============================================================
}
//============================================================
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment