php 生成验证码图片不显示问题
今天在做一个php验证码程序时发现生成出来的图片不显示,开始以为是php gd库未打开,查用phpinfo查了是可以打开的啊,下面小编来给大家介绍此问题解决办法。
清除了bom,代码也是顶行开始写的,gd库也是开启的,从这里来看估计不是gd库的问题了,可能出在程序那句代码上。
生成验证码的代码:
- <?php
 - /*
 - * 验证码产生程序
 - */
 - $letter = '';
 - //获取随机数字
 - for ($i=0; $i<2; $i++) {
 - $letter .= chr(mt_rand(48,57));
 - }
 - //获取随机字母
 - for ($i=0; $i<2; $i++) {
 - $letter .= chr(mt_rand(65,90));
 - }
 - //重构字符顺序
 - $strs = str_split($letter);
 - shuffle ($strs);
 - $rndstring = "";
 - while (list ( , $str) = each ($strs)) {
 - $rndstring .= $str;
 - }
 - //如果支持GD,则绘图
 - if(function_exists("imagecreate"))
 - {
 - //向浏览器写入cookie
 - setcookie("zjs_ckstr", md5( strtolower($rndstring) ), time()+300,'/');//验证码有效期5分钟
 - $rndcodelen = strlen($rndstring);
 - //图片大小
 - $im = imagecreate(100,30);
 - //$im = imagecreatefromgif("code.gif");
 - //字体
 - $font_type = dirname(dirname(__FILE__))."/data/font/AvantGardeBookBT.ttf";
 - //背景颜色
 - $backcolor = imagecolorallocate($im,255,255,255);
 - //字体色
 - //不支持 imagettftext
 - $fontColor = ImageColorAllocate($im, 0,0,0);
 - //支持 imagettftext
 - $fontColor2 = ImageColorAllocate($im, 0,0,0);
 - //阴影
 - $fontColor1 = ImageColorAllocate($im, 255,255,25);
 - //添加背景杂点
 - $pixColor = imagecolorallocate($im, 199, 199, 199);//杂点颜色
 - for($j=0; $j<1000; $j++){
 - imagesetpixel($im, rand(0,100), rand(0,30), $pixColor);
 - }
 - //添加背景线
 - for($j=0; $j<=3; $j++){
 - //背景线颜色
 - $lineColor1 = ImageColorAllocate($im, rand(0, 255),rand(0, 255),rand(0, 255));
 - //背景线方向大小
 - imageline($im,rand(0,40),rand(3,25),rand(40,88),rand(3,25),$lineColor1);
 - }
 - $strposs = array();
 - //文字
 - for($i=0;$i<$rndcodelen;$i++){
 - if(function_exists("imagettftext")){
 - $strposs[$i][0] = $i*16+17;//x轴
 - $strposs[$i][1] = mt_rand(20,23);//y轴
 - imagettftext($im, 5, 5, $strposs[$i][0]+1, $strposs[$i][1]+1, $fontColor1, $font_type, $rndstring[$i]);
 - } else{
 - imagestring($im, 5, $i*16+7, mt_rand(2, 4), $rndstring[$i], $fontColor);
 - }
 - }
 - //文字
 - for($i=0;$i<$rndcodelen;$i++){
 - if(function_exists("imagettftext")){
 - imagettftext($im, 16,5, $strposs[$i][0]-1, $strposs[$i][1]-1, $fontColor2, $font_type, $rndstring[$i]);
 - }
 - }
 - header("Pragma:no-cachern");
 - header("Cache-Control:no-cachern");
 - header("Expires:0rn");
 - //输出特定类型的图片格式,优先级为 gif -> jpg
 - if(function_exists("imagegif")){
 - header("content-type:image/gifrn");
 - imagegif($im);
 - }else{
 - header("content-type:image/jpegrn");
 - imagejpeg($im);
 - }
 - ImageDestroy($im);
 - }
 - ?>
 
感觉是不是没有问题了,后来百度发现一高人说关键是加入了ob_clean,了这个让我想了原因。
解决办法:ob_clean();关键代码,防止出现'图像因其本身有错无法显示'的问题,加到 header 输出之前,代码如下:header('Content-Type: image/png');