Generating Images Dynamically (with PHP)
In this article I'm going to briefly go over how to create a PHP file which will create a small loading bar which shows the value passed to it.
To begin, we create a file such as image_gen.php and the following is what I would use for a simple "loading bar". This isn't a tutorial as much as it is an example to learn from; the code is commented and is quite straight-forward and can handle errors.
<?php //Set up initial values $val = (( isset($_GET['val']) )?($_GET['val']):(false) ); $text_val = ''; //Width and height of loading bar $width = 100; $height = 12; $im = imagecreate( $width, $height ); $white = imagecolorallocate( $im, 255, 255, 255 ); $grey = imagecolorallocate( $im, 205, 207, 212 ); $green = imagecolorallocate( $im, 113, 213, 112 ); //Outline of loading bar imagerectangle( $im, 0, 0, $width-1, $height-1, $grey ); //Sanitise input, make sure it is 0 <= value <= 100 if( $val === false || !is_numeric($val) ){ $text_val = 'ERROR: NO VALUE'; } elseif( $val < 0 ){ $val = 0; $text_val = '0%'; } elseif( $val > 100 ){ $val = 100; $text_val = '100%'; } else{ $text_val = $val.'%'; } //The main loading bar drawn here imagefilledrectangle( $im, 1, 1, ($width-2)*($val/100), $height-2, $green ); //Draw the value as text. //Decides whether to draw in the bar or after the bar if( $val < 50 ){ imagestring( $im, 1, ($width-2)*($val/100) + 5, 2, $text_val, $green ); } else{ imagestring( $im, 1, ($width-2)*($val/100) - (imagefontwidth(1)*4), 2, $text_val, $white ); } //Set content-type, output gif and destroy image header('Content-type:image/gif'); imagegif($im); imagedestroy( $im );
Example Output
- image_gen.php?val=5
-
- image_gen.php?val=66
-
- image_gen.php?val=500
-
- image_gen.php?val=na
-


