1. 程式人生 > >驗證碼點選更換

驗證碼點選更換

首先需要先建立一個字串,並放好要生成驗證碼的字元,去掉了不容易識別的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);