首先我們先創建一個字符串,並放好要生成驗證碼的字符,其中我們去掉了不容易識別的i,l,o ,I,L,O
//字符串,去掉不容易識別的i,l,o ,I,L,O
$str = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789";
然後我們再創建一個大小合適的畫布填充一個顏色並輸出
<?php
//案例:生成驗證碼
header('content-type:image/png');
//字符串,去掉不容易識別的i,l,o ,I,L,O
$str = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789";
//創建畫
$width = 200;
$height = 100;
$img = imagecreatetruecolor($width,$height);
//顏色
$color = imagecolorallocate($img,0xcc,0xcc,0xcc);
//填充
imagefill($img,0,0,$color);
//輸出畫布
imagepng($img);
//銷燬畫布
imagedestroy($img);
然後我們再來畫噪點,我們讓它隨機生成100個噪點,位置隨機,顏色也隨機生成
//畫噪點
for($i=0;$i<100;$i++){
$color=imagecolorallocate($img,rand(0,100),rand(0,100));
$x=rand(0,$width);
$y=rand(0,$height);
imagesetpixel($img,$x,$y, $color);
}
畫完噪點我們再來畫噪線,噪線要畫的少一些,我們隨機生成30個噪線,位置隨機,顏色也隨機
//畫噪線
for($i=0;$i<30;$i++){
$color=imagecolorallocate($img,rand(0,100),rand(0,100));
$x1=rand(0,$width);
$y1=rand(0,$height);
$x2=rand(0,$width);
$y2=rand(0,$height);
imageline($img,$x1,$y1,$x2,$y2,$color)
}
畫完噪點,噪線我們就可以生成驗證碼了,生成4位的驗證碼,我們就需要循環四次,
首先我們要獲得整個字符串的長度,$len = strlen($str); 然後我們來生成隨機數,$index = rand(0,$len-1);然後我們去取出它的字符,我們從index的位置取,取一個.$chr = substr($str,$index,1);
//畫文字
$len = strlen($str);
$font = "simsunb.ttf";
for($i=0;$i<4;$i++){
$color=imagecolorallocate($img,255,0,0);
$index = rand(0,$len-1);
$chr = substr($str,$index,1);
$x = 20+$i*50;
$y=80;
imagettftext($img,40,rand(-70,70),$x,$y,$font,$chr);
}
然後我們根據畫布大小來調整好驗證碼的大小和位置,完整版代碼如下
<?php
//案例:生成驗證碼
header('content-type:image/png');
//字符串,去掉不容易識別的i,l,o ,I,L,O
$str = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789";
//創建畫
$width = 200;
$height = 100;
$img = imagecreatetruecolor($width,$height);
//顏色
$color = imagecolorallocate($img,0xcc,0xcc,0xcc);
//填充
imagefill($img,0,0,$color);
//畫噪點
for($i=0;$i<100;$i++){
$color=imagecolorallocate($img,rand(0,100),rand(0,100));
$x=rand(0,$width);
$y=rand(0,$height);
imagesetpixel($img,$x,$y, $color);
}
//畫噪線
for($i=0;$i<30;$i++){
$color=imagecolorallocate($img,rand(0,100),rand(0,100));
$x1=rand(0,$width);
$y1=rand(0,$height);
$x2=rand(0,$width);
$y2=rand(0,$height);
imageline($img,$x1,$y1,$x2,$y2,$color)
}
//畫文字
$len = strlen($str);
$font = "simsunb.ttf";
for($i=0;$i<4;$i++){
$color=imagecolorallocate($img,255,0,0);
$index = rand(0,$len-1);
$chr = substr($str,$index,1);
$x = 20+$i*50;
$y=80;
imagettftext($img,40,rand(-70,70),$x,$y,$font,$chr);
}
//輸出畫布
imagepng($img);
//銷燬畫布
imagedestroy($img);