利用GD的代码最终出现一个错误;图像不能被显示”;


Code utilizing GD ending up in an error that "image cannot be displayed"

我的代码如下:

<?php
session_start();
$img=imagecreatetruecolor(150,50);
$white=imagecolorallocate($img,255,255,255);
$black=imagecolorallocate($img,0,0,0);
$red=imagecolorallocate($img,255,0,0);
$pink=imagecolorallocate($img,200,0,150);
$grey=imagecolorallocate($img,150,150,150);
$blue=imagecolorallocate($img,0,204,255);
$redd=imagecolorallocate($img, 153, 0,0);
function randomString($length){
    $chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ023456789";
    srand((double)microtime()*1000000);
    $str="";
    while($i<=$length){
        $num=rand() % 33;
        $tmp=substr($chars,$num,1);
        $str.=$tmp;
        $i++;
    }
    return $str;
}
for($i=0;$i<=rand(1,5);$i++)
{
    $color=(rand(1,2)==1)? $grey:$white;
    imageline($img, rand(5,50),rand(5,50),rand(50,150) , rand(5,50), $color);
}
$ran=randomString(rand(3,6));
$_SESSION['captcha']=$ran;
imagefill($img,0,0,$redd);
imagettftext($img,14,7,23,27,$black,"fonts/times_new_yorker.ttf",$ran);
imagettftext($img,16,10,18,30,$white,"fonts/times_new_yorker.ttf",$ran);
header("Content-type:image/png");
imagepng($img);
imagedestroy($img);
?>

昨天这一切都如预期的那样。但现在Firefox显示了一条消息:

无法显示此图像,因为其中包含错误。

当我搜索任何解决方案时,似乎每个人都在谈论启用GD。但在我的代码中,GD启用的,直到今天早上,这段代码都运行得很好。

有人能帮我找到解决方案吗?

图像无法显示,因为PHP报告错误,header('Content-Type: image/png')告诉它将页面显示为图像。

要查看错误,您应该删除以下部分:

header("Content-type:image/png");
imagepng($img);
imagedestroy($img);

或者更好的是,用if (!isset($_GET['debug']))语句包围它。这样,您就可以将?debug=1附加到URL中,并查看所有可能的PHP错误,同时图像仍然正常显示。

有几种可能的解决方案可以解释为什么您的代码可能在不更改的情况下停止工作。我的猜测是您以某种方式篡改了环境。

  • session_start()需要将会话数据存储在本地驱动器的目录中。你的PHP可以访问那个目录吗
  • 字体fonts/times_new_yorker.ttf可能会消失
  • 您本可以将脚本移到Linux机器上,在那里字母大小写很重要。你确定字体的路径中不应该有大写字符吗

此外,只有几个提示:

  • 您不需要调用srand(),它是自动初始化的。(我想你来自C/C++背景)
  • 应该使用mt_rand(),而不是使用rand(),因为它更快,提供更好的随机性
  • 不应该使用幻数,而应该使用有意义的表达式(例如,将% 33替换为% strlen($chars)
  • 由于您似乎显示了一个captcha,请考虑将0O1l匹配为同一个"字符",这样就可以原谅用户的合理错误。(如果你已经这么做了,请原谅。)
相关文章: