PHP開發(fā)驗(yàn)證碼教程之添加內(nèi)容
在上節(jié)內(nèi)容中我們已經(jīng)制作好了一個(gè)畫布
下面我們把分配的顏色改成白色,代碼如下:
<?php //第一步 創(chuàng)建一個(gè)畫布 $image = imagecreatetruecolor(100, 30); //創(chuàng)建一個(gè)寬為100高為30的黑色圖像 $bgcolor = imagecolorallocate($image, 255, 255, 255); //為圖像分配顏色 imagefill($image,0,0,$bgcolor); //給黑色的背景圖像分配白色 //輸出圖像 header("content-type:image/png"); imagepng($image); //銷毀資源 imagedestroy($img); ?>
接下來我們要添加內(nèi)容了,例如添加4個(gè)隨機(jī)數(shù)
那么我們就要使用循環(huán)來操作了
for($i=0;$i<4;$i++){
//首先我們先設(shè)置下字體的大小
$fontsize = 6 ;
//然后我們?cè)O(shè)置一下文字的顏色,
$fontcolor = imagecolorallocate($image,rand(1,120),rand(1,120),rand(1,120));
// 設(shè)置內(nèi)容是一個(gè)0-9的隨機(jī)數(shù)
$fontcontent = rand(0,9);
//接下來我們要把文字填充到畫布上,但是填充到什么位置呢,所以我們要設(shè)置坐標(biāo)
$x = ($i*100/4)+rand(5,10);
$y = rand(5,10);
imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
這樣我們就在畫布上填充了0-9的數(shù)字了,完整代碼如下:
<?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); } //輸出圖像 header("content-type:image/png"); imagepng($image); //銷毀資源 imagedestroy($img); ?>