| simplepng.php |
| As a first example, consider the PHP file used in the previous True Color/Index Color examples and below. The file is called with a single parameter: the six digit hexadecimal representation of an RGB color, and returns a 50 x 50 pixel PNG set to that color. |
 |
<img src="simplepng.php?color=927B7E"> |
|
|
int imageColorAllocate ( resource image, int red, int green, int blue)
Returns a color identifier representing the color composed of the given RGB components. The im argument is the return from the imageCreate() function. red, green and blue are the values of the red, green and blue component of the requested color respectively. These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF. imageColorAllocate() must be called to create each color that is to be used in the image represented by image.
In the event that all 256 colors have already been allocated, imageColorAllocate() will return -1 to indicate failure.
|
|
<?PHP
error_reporting(E_ALL ^ E_NOTICE);
/* simplepng.php Generates a 50 x 50 pixel png of the color passed in parameter 'color' */
// convert guaranteed valid hex value to array of integers $imColor = hex2int(validHexColor($_REQUEST['color']));
// Step 1. Create a new blank image $im = imageCreate(50,50);
// Step 2. Set background to 'color' $background = imageColorAllocate($im, $imColor['r'], $imColor['g'], $imColor['b']);
// Step 3. Send the headers (at last possible time) header('Content-type: image/png');
// Step 4. Output the image as a PNG imagePNG($im);
// Step 5. Delete the image from memory 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($hex, 0, 2)), // 1st pair of digits 'g' => hexdec(substr($hex, 2, 2)), // 2nd pair 'b' => hexdec(substr($hex, 4, 2)) // 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 ; }
?>
|
|
| It is a good practice to keep steps 3, 4, and 5 together. If you don't wait until the last possible moment to send the headers, any errors thrown by the code will be interpreted as binary gobbeldygook and you won't see them. It also helps to maintain the important habbit of destorying images by doing it immediately after you output or save them. |