PHP GD: The image cannot be displayed because it contains errors

我只是一个虾纸丫 提交于 2019-12-22 09:56:12

问题


I try to make Captcha via PHP GD. But unfortunately I encounter to a problem! PHP tell me:

The image “http://127.0.0.1/par.php” cannot be displayed because it contains errors.

My code is this

<?php

  header ('Content-Type: image/png');
  $im = @imagecreatetruecolor(120, 20)
        or die('Cannot Initialize new GD image stream');
  $text_color = imagecolorallocate($im, 233, 14, 91);
  $red = imagecolorallocate($im, 255, 0, 0); 
  for ($i=0;i<=120;$i=$i+1){
      for ($j=0;$j<=20;$j=$j+1){
          imagesetpixel($im, $i,$j,$red);
      }
  }
  imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);
  imagepng($im);
  imagedestroy($im);
?>

回答1:


$im = @imagecreatetruecolor(120, 20)
      or die('Cannot Initialize new GD image stream');

You first hide the real error and TRY to display something...

which you can't display because you don't look for it,

and expose the image no matter if it really got generated.

Then you go on stackoverflow and hope someone can guess the error you might have simply suppressed using @ operator.

Make sure there is nothing before <?php and if you have, remove ?> at the end.

To make sure you have GD installed try this in a new php file:

<?php
if (extension_loaded('gd') && function_exists('gd_info')) {
    echo "PHP GD library is installed on your web server";
}
else {
    echo "PHP GD library is NOT installed on your web server";
}



回答2:


the problem is in those for

change it for:

for ($i=0; $i < 120 ; $i++) {  
    for ($j=0; $j < 20 ; $j++) { 

        imagesetpixel($im, $i,$j,$red);
    }
}

EDIT

this, is the code that i tested:

header ('Content-Type: image/png');
$im = imagecreatetruecolor(120, 20)
      or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($im, 0, 14, 91);
$red = imagecolorallocate($im, 255, 0, 0); 

for ($i=0; $i < 120 ; $i++) {  
    for ($j=0; $j < 20 ; $j++) {  

        imagesetpixel ($im ,$i,$j ,$red);
    }

 }
imagestring($im, 1, 5, 5,'A Simple Text String', $text_color);
imagepng($im);
imagedestroy($im);

result:




回答3:


This problem is occurring in FireFox only and not Chrome. You should go ahead if it´s not causing other problems. Shouldn't remove the header() even though error display disapears.




回答4:


Most probably your php outputs some warning or notices that mess up with your image data. Try to break your code before imagepng() function call to see if any errors or warnings are generated or try to stop all warnings and notices in your php.ini or with ini_set.



来源:https://stackoverflow.com/questions/24493957/php-gd-the-image-cannot-be-displayed-because-it-contains-errors

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