php图像存在错误显示不出来

2025-05-01 00:42:08
推荐回答(3个)
回答1:

看了代码后,有以下提示供参考:


1、从代码中,没有看到输出验证字符图像的代码。


2、建议编写类代码时,添加一个__construct构造函数,用于对上面的 $img 等重要参数进行初始化。


3、代码中生成验证字符的代码有些bug,会造成输出字符不足4个:


$this->code.=$this->charset[mt_rand(0, $_len)];


修正:


$this->code.=$this->charset[mt_rand(0, $_len-1)];


运行结果图:



附修改后示例代码,供参考:




回答2:

class validateCode{
private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; //随机因子
private $code; //验证码
private $codelen=4; //验证码长度
private $width=130;
private $height=50;
private $img;
//生成验证码
private function createCode(){
$_len=strlen($this->charset);
for ($i=0;$i<$this->codelen;$i++){
$this->code.=$this->charset[mt_rand(0, $_len-1)];
}
return $this->code;
}

private function createBG(){
//画布
$this->img = imagecreatetruecolor($this->width, $this->height);
$color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
imagefilledrectangle($this->img,0,0,$this->width,$this->height,$color);

$black = imagecolorallocate($this->img, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
$strx = rand(20, 8);
for ($i = 0; $i < $this->codelen; $i++) {
$strpos = rand(1, 6);
imagestring($this->img, 5, $strx, $strpos, substr($this->createCode(), $i, 1), $black);
$strx += rand(8, 14);
}

return $this->img;
}

private function outPut(){
ob_clean();
Header('Content-type:image/png');
imagepng($this->createBG());
imagedestroy($this->createBG());
}

public function doimg(){
$this->outPut();
}

}

$validate=new validateCode();
echo $validate->doimg();/

?>

回答3:

class validateCode{
private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; //随机因子
private $code; //验证码
private $codelen=4; //验证码长度
private $width=130;
private $height=50;
private $img;
//生成验证码
private function createCode(){
$_len=strlen($this->charset);
for ($i=0;$i<$this->codelen;$i++){
$this->code.=$this->charset[mt_rand(0, $_len-1)];
}
return $this->code;
}

private function createBG(){
//画布
$this->img = imagecreatetruecolor($this->width, $this->height);
$color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
imagefilledrectangle($this->img,0,0,$this->width,$this->height,$color);

$black = imagecolorallocate($this->img, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
$strx = rand(20, 8);
for ($i = 0; $i < $this->codelen; $i++) {
$strpos = rand(1, 6);
imagestring($this->img, 5, $strx, $strpos, substr($this->createCode(), $i, 1), $black);
$strx += rand(8, 14);
}

return $this->img;
}

private function outPut(){
ob_clean();
Header('Content-type:image/png');
imagepng($this->createBG());
imagedestroy($this->createBG());
}

public function doimg(){
$this->outPut();
}

}

$validate=new validateCode();
echo $validate->doimg();/

?>