PHP5中圖片驗證碼的製作

PHP5中圖片驗證碼的製作(上)
1、啓用PHP中GD庫
GD庫提供了一系列用來處理圖片的API,使用GD庫可以處理圖片,或者生成圖片。 在網站上GD庫通常用來生成縮略圖或者用來對圖片加水印或者對網站數據生成報表。
通過PHP.ini 啓用GD庫
extension=php_gd2.dll
2、部分GD庫函數的介紹
(1) imagecreatetruecolor   新建一個真彩色圖像
imagecreatetruecolor ( int x_size, int y_size ) // x就是寬 ,y就是高
(2)imagecolorallocate  爲一幅圖像分配顏色(調色板)
imagecolorallocate ( resource image, int red, int green, int blue )
(3)imagestring  繪圖函數
imagestring ( resource image, font, int x, int y, 內容 , 顏色 )
3、學習:隨機函數,十六進制函數
(1)rand 隨機函數
rand ( [int min, int max] )
rand (1,4)  隨機 1-4 之間的數
(2)dechex 十進制轉換爲十六進制
dechex ( 十進制數 )
十六進制 1 ~ f
4、GD+SESSION製作PHP驗證碼
<?php
session_start();
 for($i=0;$i<4;$i++){//生成4位隨機數
  $rand.=dechex(rand(1,15));
 }
$_SESSION[checkpic]=$rand;//把驗證碼存入session中
$im=imagecreatetruecolor(100,30);//創建一個圖片
//設置圖片顏色
$bg=imagecolorallocate($im,0,0,0);//第一次使用這個函數就是背景顏色
$te=imagecolorallocate($im,255,255,255);
//把字符卸載圖片左上角
imagestring($im,rand(1,6),25,10,$rand,$te);
//輸出圖像
header("Content-type: image/jpeg");
imagejpeg($im);
?>

 

PHP5中圖片驗證碼的製作(下)
1、image與header輸出的介紹
PHP的HEADER是定義頭的動作,新PHP5中支持三種類型:

Content-Type: xxxx/yyyy  
Location: xxxx:yyyy/zzzz
Status: nnn xxxxxx
GD庫中有對應的image類型
imagejpeg(*)   imagegif(*)   imagepng(*) ……
2、imageline 與 imagesetpixel 函數
imageline 畫線函數
imageline ( resource image, int x1, int y1, int x2, int y2, int color )
imagesetpixel 畫點函數
imagesetpixel ( resource image, int x, int y, int color )
3、imagettftext函數調用字體寫入文字
imagettftext 帶字體的寫入函數
imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )
4、PHP驗證碼插入中文的方法
iconv("gb2312","UTF-8","新年快樂!"); //首先要將文字轉換成UTF8格式
然後使用imagettftext  調用一種字體,再將轉換好的UTF8格式的中文寫入圖片中!

<?php
session_start();
 for($i=0;$i<4;$i++){//生成4位隨機數
  $rand.=dechex(rand(1,15));
 }
$_SESSION[checkpic]=$rand;
$im=imagecreatetruecolor(100,30);//創建一個圖片
//設置圖片顏色
$bg=imagecolorallocate($im,0,0,0);//第一次使用這個函數就是背景顏色
$te=imagecolorallocate($im,255,255,255);
for($i=0;$i<3;$i++){//製造直線干擾
$te2=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imageline($im,0,rand(0,30),100,30,$te2);
}
for($i=0;$i<100;$i++){//製造噪點干擾
 imagesetpixel($im,rand()%100,rand()%30,$te2);
}
$str=iconv("gbk","UTF-8","新年快樂");//設置字符編碼
imagettftext($im,12,3,20,20,$te,'SIMLI.TTF',$str);//把中文寫到圖片上
//把字符卸載圖片左上角
//imagestring($im,rand(1,6),25,10,$rand,$te);
//輸出圖像
header("Content-type: image/jpeg");
imagejpeg($im);
?>

 

發佈了37 篇原創文章 · 獲贊 2 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章