skip to content

PHP: Creating on-the-fly 'broken' images

"PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including gif, png, jpg, wbmp, and xpm. Even more convenient, PHP can output image streams directly to a browser."

PHP Source Code

This is a handy script for displaying an image place-holder in your web pages where an image is missing or something goes awry. The script returns a JPEG image at a specific width and height, containing a red box and 'X'. With a bit of work you could change this to display just about anything.

<?PHP namespace Chirp; # check and limit input values to prevent abuse if(!$width = min(640, abs(intval($width)))) $width = 240; if(!$height = min(480, abs(intval($height)))) $height = 160; # create image $img = @imagecreate($width, $height) or die("Cannot Initialize new GD image stream"); # define background colour (white) $background_color = imagecolorallocate($img, 255, 255, 255); # define line colour (red) $line_color = imagecolorallocate($img, 255, 0, 0); # draw box and lines imagerectangle($img, 0, 0, $width-1, $height-1, $line_color); imageline($img, 0, 0, $width, $height, $line_color); imageline($img, $width, 0, 0, $height, $line_color); # display the image and free memory Header("Content-type: image/jpeg"); imagejpeg($img); imagedestroy($img); exit;

The above code needs to be saved in it's own file which can be called, for example, errorimg.php. The method for displaying a 'broken' image on your page is then:

<IMG src="errorimg.php">

which will create an image using the default width and height; or you can set the width and/or height value yourself:

<IMG src="errorimg.php?width=100"> <IMG src="errorimg.php?width=100&height=100">

What does the result look like for the examples above?

You will need to compile PHP with the GD Graphics Library for this to work.



Post your comment or question