PHP invalid image's and error handling

Posted by Emdiesse on Stack Overflow See other posts from Stack Overflow or by Emdiesse
Published on 2010-04-04T14:30:06Z Indexed on 2010/04/04 14:33 UTC
Read the original article Hit count: 923

Filed under:
|
|
|

Using PHP's Image and GD functions you can use the following method to finally output the php image

imagepng($image);

Sometimes, for whatever reason the image may not be displayed typically the error is not with the image but with the actual php functions not executing successfully. However this causes a blank image to be returned which doesn't help me.

What I want to know is, is there a way to detect a blank or an invalid image and create a new image, write the errors to the new image using imagestring() and then display this new (debug) image instead.

for example, a successfully displayed image with no errors:

$image  = imagecreate(256, 256); //create image
imagecolortransparent($image, $BLUE); //set transparent
imagefilledrectangle($image, 0, 0, 256, 256, $BLUE); //fill with 'transparent colour'

//Draw a border round the image
imageline($image, 0, 0, 0, 255, $Black);
imageline($image, 0, 0, 255, 0, $Black);
imageline($image, 255, 0, 255, 255, $Black);
imageline($image, 0, 255, 255, 255, $Black);

imagestring($image, 1, 10, 10, "I am an image!", $Black);

imagepng($image);
imagedestroy($image);

but if I then introduce some errors in the php script that may or may not be to do with the actual image creation then the php script fails and the image will not be visible...

$image  = imagecreate(256, 256); //create image
imagecolortransparent($image, $BLUE); //set transparent
imagefilledrectangle($image, 0, 0, 256, 256, $BLUE); //fill with 'transparent colour'

//Draw a border round the image
imageline($image, 0, 0, 0, 255, $Black);
imageline($image, 0, 0, 255, 0, $Black);
imageline($image, 255, 0, 255, 255, $Black);
imageline($image, 0, 255, 255, 255, $Black);

imagestring($image, 1, 10, 10, "I am an image!", $Black);

/* I am here to cause problems with the php script 
** and cause the execution to fail, I am a function 
** that does't exist...
**
** and I am missing a semi colon! ;)*/
non_existant_function() 

imagepng($image);
imagedestroy($image);

At this point I want to create a new image like above but in replacement of the I am an image! text I would put the actual error that has occured.

© Stack Overflow or respective owner

Related posts about php

Related posts about gd