[原创]一个效果还不错的验证码程序代码
| |
Posted in PHP on 2009/06/10 / 引用(0)
最近感觉以前使用的验证码生成函数太差,优化了一下代码,新的效果如下:
点击在新窗口中浏览此图片

字体文件:


源程序:



<?php
$width = "90";
$height = "30";
$charlen = "4";
$bgcolor = "#eeeeee";
$noise = true;
$noisenum = 20;
$border = false;
$bordercolor = "#cccccc";
$font = dirname(__FILE__). "/plugins/ENGR.TTF";
generate($width,$height,$charlen,$font,$bgcolor,$noise,$noisenum,$borer,$bordercolor);

function generate($width,$height,$len,$font,$bgcolor,$noise,$noisenum,$borer,$bordercolor){
    //创建画布
    $image = imagecreatetruecolor ( $width, $height );
    $back = getcolor ($image, $bgcolor );
    imageFilledRectangle ( $image, 0, 0, $width, $height, $back );
    $size = ($width-6) / $len;
    $size = ($size > $height)?$height:$size;

    //为画布添加杂点
    if ($noise == true){
      for($i = 0; $i < $noisenum; $i++) {
        $randColor = imageColorAllocate ( $image, rand ( 150, 255 ), rand ( 150, 255 ), rand ( 150, 255 ) );
        $x1 = rand(0,$width);
        $y1 = rand(0,$height);
        $x2 = $x1+rand(-20,20);
        $y2 = $y1+rand(-20,20);
        imageline ( $image, $x1, $y1,  $x2,  $y2,  $randColor );
      }
    }

    //生成随机数字

    $textall = "0123456789ABCDEFGHHJKLMNPQRSTWXY";
    $code = '';
    $colorArr = array("#006633","#990000","#006699","#663333");
    $angleArr = array(10,-10,-20,20);
    $textColor = getcolor($image,$colorArr[array_rand($colorArr)]);

    //echo $textColor;
    for($i = 0; $i < $len; $i ++) {
      $tmptext = rand ( 0, 31 );
      $randtext = $textall [$tmptext];
      imagettftext ( $image,18, $angleArr[array_rand($angleArr)], 6+$size*$i, 24, $textColor, $font, $randtext );
      $code .= $randtext;
    }
    $_SESSION ['validatecode'] = $code;

    //加上边框
    if ($border == true){
      $bordercolor = getcolor ( $image, $bordercolor );
      imageRectangle ( $image, 0, 0, $width - 1, $height - 1, $bordercolor );
    }


    //生成
    header ( "Content-type: image/png" );
    imagePng ( $image );
    imagedestroy ( $image );
    die;
  }
  function getcolor(&$image,$color) {
    $color = eregi_replace ( "^#", "", $color );
    $r = $color [0] . $color [1];
    $r = hexdec ( $r );
    $b = $color [2] . $color [3];
    $b = hexdec ( $b );
    $g = $color [4] . $color [5];
    $g = hexdec ( $g );
    $color = imagecolorallocate ( $image, $r, $b, $g );
    return $color;
  }

?>

点击在新窗口中浏览此图片
This entry comes from 本站原创 and has been read for 899 times.It is tagged with .
2 Responses
suchasplus Email Homepage says:
at 2010/07/21 02:30
好赞,收藏备用
Fleng says:
at 2009/10/20 15:22
呵呵。。不错。。。下来看看cool
分页: 1/1 第一页 1 最后页
发表评论

昵称

网址

电邮

OpenID登入 高级选项 表情