我编写了一段代码,使用GD在PHP中从文本生成图像。当我在XAMPP本地主机上运行此代码时,我没有得到任何错误,但是也没有得到任何图像。
Generate.php
<?php
session_start() ;
header ('Content-type: image/jpeg') ;
$_SESSION['secure'] = rand(1000,9999) ;
$text=$_SESSION['secure'] ;
$font_size=30 ;
$img_height=40 ;
$img_width=100 ;
$image=imagecreate($image_width,$image_height) ;
imagecolorallocate($image,255,255,255) ;
$text_color=imagecolorallocate($image,0,0,0) ;
imagettftext($image,$font_size,0,15,30,$text_color,'captchafont.ttf',$text) ;
imagejpeg($image) ;
?>
HTML
<img src="generate.php"/>
在本地主机上运行此HTML文件时得到的全部是在浏览器中找不到图像符号。
您应更改此行:
$image=imagecreate($image_width,$image_height) ;
进入
$image=imagecreate($img_width,$img_height) ;
因为您定义了$img_width
和$img_height
变量,而不是$image_width
和$image_height
您还应确保captchafont.ttf
存在于正确的路径中并以正确的方式使用。从手册:
取决于何时使用PHP的GD库版本fontfile不能以/开头,然后.ttf将附加到文件名,并且库将尝试搜索该文件名沿着库定义的字体路径。
关于测试的小建议
注释/删除行header ('Content-type: image/jpeg') ;
,并在浏览器中简单运行此URL,例如http://localhost/generate.php
,以确保没有错误出现。否则,如果仍然没有在文件开头添加error_reporting(E_ALL)
。删除所有错误和警告后,您当然应该用header
删除此行和取消注释行,然后检查图像是否正确显示。