tags:

views:

84

answers:

1

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.

+1  A: 

What you want to do is catch PHP errors, not detect a "blank image". You can use set_error_handler() to define a custom callback that's called when an error occurs.

Things such as parse errors are something you should debug before publishing your code, but this should help you detect random errors (database connections dying, whatnot).

Matti Virkkunen