最近正在学习PHP,在作验证码时出现了问题,就是图片没法显示,首先检查GD2是支持的,换了好几个PHP版本也不行,最终找到的解决的方法,首先看下面的代码:
代码一:
php
代码是没有任何问题的,可是没法显示图片。解决方案:为了可以显示,必须在header前加入ob_clean()函数,问题就解决了。ob_clean()函数是为了清除输出缓存区的内容,由于在绘制图片是会生成许多图片类的文件,要正常显示的话,必需要清除缓冲区内容。缓存
<?phpsession
session_start();
dom
$_width=75;ide
$_height=25;函数
$_code_num=4;学习
//生成四个随机数,固然更多也是能够的
spa
for ($i = 0; $i < $_code_num; $i++) {code
$_num.=dechex(mt_rand(0, 15));图片
}
//将随机数放到session中保存
$_SESSION["code"]=$_num;
//建立图片
$_img_png=p_w_picpathcreatetruecolor($_width, $_height);
//设置颜色
$_color=p_w_picpathcolorallocate($_img_png,255,255,255);
//将设置的颜色填充
p_w_picpathfill($_img_png, 0, 0, $_color);
//设置验证码边框
// $_black_border=p_w_picpathcolorallocate($_img_png, 255,255, 255);//边框是白色
// p_w_picpathrectangle($_img_png, 0, 0,$_width-1 , $_height-1,$_black_border);
//随机画出六条线条 使用p_w_picpathline;
for($i=0;$i<6;$i++){
$_random_color=p_w_picpathcolorallocate($_img_png, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
p_w_picpathline($_img_png, mt_rand(0, $_width), mt_rand(0, $_height), mt_rand(0, $_width), mt_rand(0, $_height), $_random_color);
}
//随机画出雪花
for($i=0;$i<100;$i++){
$_random_color=p_w_picpathcolorallocate($_img_png, mt_rand(200,255), mt_rand(200,255), mt_rand(200,255));
p_w_picpathstring($_img_png, 1, mt_rand(1, $_width), mt_rand(1, $_height),''*'', $_random_color);
}
//将四位验证码放进去
for($i=0;$i<$_code_num;$i++){
$_code_color=p_w_picpathcolorallocate($_img_png, mt_rand(0,170), mt_rand(0,170), mt_rand(0,170));
p_w_picpathstring($_img_png, 5, $i*$_width/4+mt_rand(1, 9), mt_rand(1,$_height/2), $_SESSION["code"][$i], $_code_color);
}
//输出图片
header("Content-Type:p_w_picpath/png");//设置类型是图片类型;
p_w_picpathpng($_img_png);
p_w_picpathdestroy($_img_png);
?>
注:若是没有使用ob_clean()函数,还有一种方法是<?php?>必须顶头写,并且内部第一行不能出现任何空行,php内部的代码也要顶头写。