PHP invalid image's and error handling

十年热恋 提交于 2019-12-02 01:24:51

问题


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:


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).



来源:https://stackoverflow.com/questions/2574713/php-invalid-images-and-error-handling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!