這篇文章主要介紹了PHP基于GD2函數庫實現驗證碼功能,簡單介紹了GD2函數庫的常用函數,并結合實例形式分析了php實現驗證碼功能相關操作技巧,需要的朋友可以參考下。
本文實例講述了PHP基于GD2函數庫實現驗證碼功能,分享給大家供大家參考,具體如下:
在正式制作驗證碼之前要先補充點知識,PHP使用GD2函數庫實現對各種圖形圖像的處理,所以我們制作驗證碼主要要使用到一些GD2函數庫里的一些函數:
imagecreatetruecolor($width,$height)函數,主要用于創建畫布,有2個參數width和height是必選的,代表你所要創建的畫布的長和寬;
imagecolorallocate($image, $red, $green, $blue)函數,主要用于填充圖像,第1個參數是你所創建的圖像的標識符,后面3個參數是顏色的RGB設置;
imagefill($image, $x, $y, $color)函數,第一個函數是你創建的圖像標識符,第2、3個參數$x、$y是左上角坐標,最后一個參數是你要填充顏色;
imagestring($image, $font, $x, $y, $string, $color)函數設置文字,且imagestring()函數如果直接繪制中文字符串會出現亂碼,如果要繪制中文字符串可以使用imagettftext()函數;
imagepng($image[,$filename])函數以phg格式將圖像輸出到瀏覽器或者保存為文件,第1個參數為你創建的圖像標識號,第2個參數為可選參數,你要保存文件的文件名;
imagesetpixel($image, $x, $y, $color)函數畫單個像素點;
imageline($image, $x1, $y1, $x2, $y2, $color)函數畫一條線段,$x1、$y1是線段是左上角坐標,$x2、$y2是線段的右下角坐標。
代碼主要如下:
- <?php
- //創建畫布
- $img = imagecreatetruecolor(100, 50);
- //創建顏色
- $black = imagecolorallocate($img, 0x00, 0x00, 0x00);
- $green = imagecolorallocate($img, 0x00, 0xFF, 0x00);
- $white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF);
- //畫布填充顏色
- imagefill($img, 0, 0, $white);//背景為白色
- //生成隨機驗證碼
- $code = make(5);
- //設置文字
- imagestring($img, 5, 10, 10, $code, $black);//黑字
- //加入噪點干擾
- for ($i = 0; $i <300; $i++){
- imagesetpixel($img, rand(0, 100), rand(0, 100), $black);
- imagesetpixel($img, rand(0, 100), rand(0, 100), $green);
- }
- //加入線段干擾
- for ($n = 0; $n <=1; $n++){
- imageline($img, 0, rand(0, 40), 100, rand(0, 40), $black);
- imageline($img, 0, rand(0, 40), 100, rand(0, 40), $white);
- }
- //輸出驗證碼
- header("content-type: image/png");//告訴瀏覽器這個文件是一個png圖片
- imagepng($img);
- //銷毀圖片,釋放內存
- imagedestroy($img);
- //生成隨機驗證碼的函數
- function make($length){
- $code = 'abcdefghijklmnopqrsruvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
- //str_shuffle()函數用于打亂字符串
- return substr(str_shuffle($code), 0, $length);
- }
- ?>
新聞熱點
疑難解答