PHP開發(fā)驗(yàn)證碼教程之干擾元素(線)
上節(jié)我們已經(jīng)使用了加入干擾元素(點(diǎn))
下面我們來加入干擾元素(線)
<?php //第一步 創(chuàng)建一個(gè)畫布 $image = imagecreatetruecolor(100, 30); //創(chuàng)建一個(gè)寬為100高為30的黑色圖像 $bgcolor = imagecolorallocate($image, 255, 255, 255); //為圖像分配顏色 imagefill($image,0,0,$bgcolor); //給黑色的背景圖像分配白色 //第二步,在這個(gè)圖像上實(shí)現(xiàn)數(shù)字 for($i=0;$i<4;$i++){ $fontsize = 6; //字體大小 $fontcolor = imagecolorallocate($image,rand(1,120),rand(1,120),rand(1,120)); //設(shè)置字體的顏色 顏色我們給一個(gè)隨機(jī)的值,畫布為白色,0到120之間,顏色為深色 $fontcontent = rand(0,9); //設(shè)置內(nèi)容是一個(gè)隨機(jī)數(shù) //現(xiàn)在需要把這個(gè)隨機(jī)數(shù)添加到畫布上去 $x = ($i*100/4)+rand(5,10); $y = rand(5,10); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); } //設(shè)置干擾元素 點(diǎn) for($i=0;$i<200;$i++){ //首先我們?cè)O(shè)置點(diǎn)的顏色 $pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200)); //設(shè)置點(diǎn)放在圖像的什么位置上 imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor); } //輸出圖像 header("content-type:image/png"); imagepng($image); //銷毀資源 imagedestroy($img); ?>
上面代碼我們是加入了干擾元素? 點(diǎn)
我們來看一下加入干擾元素,線
for($i=0;$i<5;$i++){
//首先我們?cè)谘h(huán)中設(shè)置了,線的條數(shù)為5條
//設(shè)置線條的顏色,文字的顏色是1,120之間,那么我們線的顏色要比文字顏色要淺,設(shè)置80,220
$linecolor = imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));?
//然后設(shè)置線的位置
imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);
}
下面我們來看一下完整代碼:
<?php //第一步 創(chuàng)建一個(gè)畫布 $image = imagecreatetruecolor(100, 30); //創(chuàng)建一個(gè)寬為100高為30的黑色圖像 $bgcolor = imagecolorallocate($image, 255, 255, 255); //為圖像分配顏色 imagefill($image,0,0,$bgcolor); //給黑色的背景圖像分配白色 //第二步,在這個(gè)圖像上實(shí)現(xiàn)數(shù)字 for($i=0;$i<4;$i++){ $fontsize = 6; //字體大小 $fontcolor = imagecolorallocate($image,rand(1,120),rand(1,120),rand(1,120)); //設(shè)置字體的顏色 顏色我們給一個(gè)隨機(jī)的值,畫布為白色,0到120之間,顏色為深色 $fontcontent = rand(0,9); //設(shè)置內(nèi)容是一個(gè)隨機(jī)數(shù) //現(xiàn)在需要把這個(gè)隨機(jī)數(shù)添加到畫布上去 $x = ($i*100/4)+rand(5,10); $y = rand(5,10); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); } //第三步,設(shè)置干擾元素,點(diǎn) for($i=0;$i<200;$i++){ $pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200)); //設(shè)置點(diǎn)的顏色 imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor); } for($i=0;$i<5;$i++){ $linecolor = imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220)); //設(shè)置線的顏色 讓線的顏色變得更淺一點(diǎn),80到220 imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor); } //輸出圖像 header("content-type:image/png"); imagepng($image); //銷毀資源 imagedestroy($img); ?>
如上代碼,我們就制作了一個(gè)簡(jiǎn)單的驗(yàn)證碼