1. 程式人生 > >php 驗證碼 生成 字型變化 可高低 傾斜 大小

php 驗證碼 生成 字型變化 可高低 傾斜 大小

<?php

/*
@author sanshi
    QQ:35047205
    Email:[email protected]
    MSN:[email protected]
*/

$string=md5(rand(1,1000));
$string=substr($string,0,4);
$len=strlen($string);
$bordercolor = "#000000";
$bgcolor = "#ffffff";//背景色
$height = 30;
$width  = 60;

$image = imageCreate($width, $height);
//畫邊框
$bordercolor = getcolor($image,$bordercolor);
imagefilledrectangle($image,0,0,$width+1,$height+1,$bordercolor);
//畫背景
$back = getcolor($image,$bgcolor);
imagefilledrectangle($image,1,1,$width-2,$height-2,$back);
//畫干擾元素
$num = 200; //干擾元素的個數
setnoise($image,$width,$height,$num);
//字型大小
$size = ceil($width / $len);
//寫字

for($i=0;$i<$len;$i++)
{
 $TempText=substr($string,$i,1);
 //字型顏色
 $textColor = imageColorAllocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
 //取得隨機大小
 $randsize =rand($size-$size/6,$size+$size/6);
 //取得字型
 $font = rand(1,1).".ttf";
 //取得角度
 $randAngle = rand(-15,15);
 //取得每次的位置
  $x=8+($width-$width/8)/$len*$i;
 //echo "<br>";
 //取得每次的高度
 $y=rand($height-3,$height-10);
 imagettftext($image,$randsize,$randAngle,$x,$y,$textColor,$font,$TempText);  
}
header("Content-type: image/png");
imagePng($image);
imagedestroy($image);
//取得色彩
function getcolor($image,$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($image,$width,$height,$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);
 }
}
?>

圖片看不到,生成的.png圖象