`
gzycnet
  • 浏览: 31193 次
  • 性别: Icon_minigender_1
  • 来自: 贵阳
社区版块
存档分类
最新评论

生成图片验证码

PHP 
阅读更多
废话少说,代码均已注释。
<?php
$width = "70";//图片宽
$height = "25";//图片高
$len = "4";//生成几位验证码
$bgcolor = "#ffffff";//背景色
$noise = true;//生成杂点
$noisenum = 200;//杂点数量
$border = false;//边框
$bordercolor = "#000000"; //边框颜色
$image = imageCreate($width, $height); //创建指定宽度和高度的图片
$back = getcolor($bgcolor);
imageFilledRectangle($image, 0, 0, $width, $height, $back);
$size = $width/$len;
if($size>$height) $size=$height;
$left = ($width-$len*($size+$size/10))/$size;
for ($i=0; $i<$len; $i++)
{
        $randtext = rand(0, 9);  //随即生成数字
        $code .= $randtext;
 $textColor = imageColorAllocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
 $font = rand(1,4).".ttf";  //随机选择的字体
 $randsize = rand($size-$size/10, $size+$size/10);//随机的大小
 $location = $left+($i*$size+$size/10);
 imagettftext($image, $randsize, rand(-18,18), $location, rand($size-$size/10, $size+$size/10), $textColor, $font, $randtext); 
}
if($noise == true) setnoise();
$bordercolor = getcolor($bordercolor); 
if($border==true) imageRectangle($image, 0, 0, $width-1, $height-1, $bordercolor);
header("Content-type: image/png");
imagePng($image);
imagedestroy($image);
function getcolor($color)
{
     global $image;
     $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;
}
function setnoise()
{
 global $image, $width, $height, $back, $noisenum;
 for ($i=0; $i<$noisenum; $i++){
  $randColor = imageColorAllocate($image, rand(0, 255), rand(0, 255), rand(0, 255));  
  imageSetPixel($image, rand(0, $width), rand(0, $height), $randColor);
 } 
}
?>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics