The Interactive Example Source

 

 

red:
 green:
blue:
or
 hex:

  

rgb.php

rgb.png

<?PHP


error_reporting
(E_ALL E_NOTICE);

/*
rgb.php
An interactive example of the additive nature of the RGB color model
*/

if (isset($_REQUEST['hex'])) { 
    
// if a hex value is passed, use it
    
$imColor hex2int(validHexColor($_REQUEST['hex'])) ;
} else {
    
// otherwise use red, green, & blue values
    
$imColor['r'] = validIntColor($_REQUEST['red']);
    
$imColor['g'] = validIntColor($_REQUEST['green']);
    
$imColor['b'] = validIntColor($_REQUEST['blue']);
}

$im imageCreateFromPNG('rgb.png') ;

// determine the indicies of white and the three primaries 
$rIndex imageColorExact ($im0xFF0x000x00); // get index of red
$gIndex imageColorExact ($im0x000xFF0x00); // get index of green
$bIndex imageColorExact ($im0x000x000xFF); // get index of blue
$wIndex imageColorExact ($im0xFF0xFF0xFF); // get index of white

// redefine the colors to the input value
// first set pure red, green, and blue portions to their respective components of $imColor 
imageColorSet($im$rIndex$imColor['r'], 00); 
imageColorSet($im$gIndex0$imColor['g'], 0); 
imageColorSet($im$bIndex00$imColor['b']); 
// then set the combined portion to all components of $imColor
imageColorSet($im$wIndex$imColor['r'], $imColor['g'], $imColor['b']);

header('Content-type: image/png');
imagePNG($im);
imageDestroy($im); 

/**
 * @param    $hex string        6-digit hexadecimal color
 * @return    array            3 elements 'r', 'g', & 'b' = int color values
 * @desc Converts a 6 digit hexadecimal number into an array of
 *       3 integer values ('r'  => red value, 'g'  => green, 'b'  => blue)
 */
function hex2int($hex) {
        return array( 
'r' => hexdec(substr($hex02)), // 1st pair of digits
                      
'g' => hexdec(substr($hex22)), // 2nd pair
                      
'b' => hexdec(substr($hex42))  // 3rd pair
                    
);
}

/**
 * @param $input string     6-digit hexadecimal string to be validated
 * @param $default string   default color to be returned if $input isn't valid
 * @return string           the validated 6-digit hexadecimal color
 * @desc returns $input if it is a valid hexadecimal color, 
 *       otherwise returns $default (which defaults to black)
 */
function validHexColor($input '000000'$default '000000') {
    
// A valid Hexadecimal color is exactly 6 characters long
    // and eigher a digit or letter from a to f
    
return (eregi('^[0-9a-f]{6}$'$input)) ? $input $default ;
}

/**
 * @param $input int    integer to be validated
 * @param $default int    default value returned if $input isn't valid
 * @return int            the validated integer
 * @desc returns $input if it is a valid integer color, 
 *       otherwise returns $default (which defaults to 0)
 */
function validIntColor($input$default 0) {
    
// A valid integer color is between 0 and 255
    
return (is_numeric($input)) ? (int) max(min($input255),0) : (int) $default ;
}

?>