找不出哪里出错了,但是预览时就是会出现一大堆乱码<?php 
ob_clean();
header("Content-Type: image/png");
$img=@imagecreatetruecolor(50,20) or die("fjhb");
$bg_color=imagecolorallocate($img,255,255,255); 
imagefill($img,0,0,$bg_color);   $border_color=imagecolorallocate($img,200,200,200);  
imagerectangle($img,0,0,49,19,$border_color);
for($i=2;$i<18;$i++){
$line_color=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
imageline($img,2,$i,47,$i,$line_color);
}
$font_size=12;
$str[0]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$str[1]="abcdefghijklmnopqrstuvwxyz";
$str[2]="01234567891234567890123456";

$imgstr[0]["s"]=$str[rand(0,2)][rand(0,25)];
$imgstr[0]["x"]=rand(2,5);
$imgstr[0]["y"]=rand(1,4);

  $imgstr[1]["s"]=$str[rand(0,2)][rand(0,25)];
$imgstr[1]["x"]=$imgstr[0]["x"]+$font_size-1+rand(0,1);
$imgstr[1]["y"]=rand(1,3);

  $imgstr[2]["s"]=$str[rand(0,2)][rand(0,25)];
$imgstr[2]["x"]=$imgstr[1]["x"]+$font_size-1+rand(0,1);
$imgstr[2]["y"]=rand(1,4);

$imgstr[3]["s"]=$str[rand(0,2)][rand(0,25)];
$imgstr[3]["x"]=$imgstr[2]["x"]+$font_size-1+rand(0,1);
$imgstr[3]["y"]=rand(1,3);

for($i=0;$i<4;$i++){
$text_color=imagecolorallocate($img,rand(50,180),rand(50,180),rand(50,180));
imagechar($img,$font_size,$imgstr[$i]["x"],$imgstr[$i]["y"],$imgstr[$i]["s"],$text_color);
}imagepng($img);
imagedestroy($img);
?>PHP图片验证码

解决方案 »

  1.   

    乱码是浏览器显示了字符而不是图片么?
    关闭浏览器重新访问这个地址试试。如果还不行,应该是header的问题。
    图片输出,最好用UTF-8字符集,因为有可能会遇到中文的输出。
    而UTF-8的话,就要注意BOM头了。
      

  2.   

    楼主很幽默ob_clean(); //清除缓冲区内容,这样即便有BOM头,也不会影响图片
    header("Content-Type: image/png"); //声明其后内容是png图片数据于是即便程序有非语法性错误,至多也只是一个叉,而不是乱码
      

  3.   

    我这里测试正常哦检查一下有没有去掉BOM头
    gd库等环境是否完备最主要的感觉还是header问题,header之前有别的输出吗?
      

  4.   

    lZ 是否预览是如下的乱码:
    出现这样的问题是因为文件编码为:
    然后你需要修改成
    就OK了,预览效果: