首页 > php 用gd库制作验证码不显示图片

php 用gd库制作验证码不显示图片

写了一个生成验证码,但是在本地wampsever环境中不能显示图片

但我上传到服务器里,却可以显示。

本地的gd库是打开的

新手弄得一头雾水,求教!

    <?php 
require_once '../include.php';
function verifyImage($type=3,$length=4,$pixel=1,$line=1,$sess_name = "verify"){
//使用GD库制作验证码
//定义画布宽高
    $width=80;
    $height=30;
//创建画布
    $image = imagecreatetruecolor ( $width, $height );
//定义画布中的颜色
    $white = imagecolorallocate ( $image, 255, 255, 255 );
    $black = imagecolorallocate ( $image, 0, 0, 0 );
//用填充矩形填充画布
    imagefilledrectangle ( $image, 1, 1, $width - 2, $height - 2, $white );
//获取字符串
    $chars=buildRandomString(3,4);
//传值验证
    $_SESSION [$sess_name] = $chars;
    $fontfiles=array("SIMYOU.TTF");
    $color = imagecolorallocate ( $image, mt_rand ( 50, 90 ), mt_rand ( 80, 200 ), mt_rand ( 90, 180 ) );
//在画布中添加字符
for($i = 0; $i < $length; $i ++) {
        $size = mt_rand ( 14, 18 );
        $angle = mt_rand ( - 15, 15 );
        $x = 5 + $i * $size;
        $y = mt_rand ( 20, 26 );
        $fontfile = '../fonts/' . $fontfiles [mt_rand ( 0, count ( $fontfiles ) - 1 )];
        $text = substr ( $chars, $i, 1 );
        imagettftext ( $image, $size, $angle, $x, $y, $black, $fontfile, $text );
    }

//添加干扰元素 点
    if ($pixel) {
    for ($i=0; $i < 50; $i++) { 
        imagesetpixel($image, mt_rand(0,$width-1), mt_rand(0,$height-1), $color);
    }
        }
//添加干扰元素 线
    if ($line) {
    for ($i=0; $i < $line; $i++) { 
        imageline($image, mt_rand(0,$width-1), mt_rand(0,$height-1),mt_rand(0,$width-1), mt_rand(0,$height-1), $color);
    }
    }
//浏览器标示输出是图像
    header ( "content-type:image/jpeg" );
//创建图像资源
    imagejpeg ( $image );
//注销图像资源
    imagedestroy($image);
}
verifyImage();
 ?>

输出验证码不能有其他内容输出的!!
针对你的情况,是因为你本地环境display_errors开启了,
你只需要在最上面,也就是require_once '../include.php'; 这一行的上面加上ini_set('display_errors', 'Off'); 就可以了。
另外你的<?php可以从头开始写,不要空格或者空行。


这段代码,为何看着如此眼熟.......!

题主应该是从慕课网上的PHP电商网站开发教程中提取出来的。

这段代码有个BUG,就是在
$fontfiles=array("SIMYOU.TTF");
$fontfile = '../fonts/' . $fontfiles [mt_rand ( 0, count ( $fontfiles ) - 1 )];

fonts文件夹中,你没有放置SIMYOU.TTF或者其他相关的字体文件,所以服务器找不到字体。

只要把TTF字体文件给补上即可。


照你们说的 改了 还是不行


图片不显示一般是因为生成的图片流不正确,你直接在浏览器里面打开这个图片的地址。
可能就你会发现:

phpFatal error :xxxxxx 
or 
Warning : xxxxx

的错误提示。

另外一般本地是开启 display_erorrs 的,但是服务器生产环境里面为了安全起见是关闭所有的错误输出的。


  1. check file encoding, utf-8 usually.
  2. try ob_clean(); to clean the wrong output buffer.
【热门文章】
【热门文章】