- <?php
- header("content-type: image/png");
- class yanzhengma{
- public $str="你是我的好朋友"; //驗證碼
- public $geshu=4;//驗證碼個數
- public $img;//圖片sourcer
- public function __construct($geshu){
- $this->geshu=$geshu; //初始化個數
- }
- public function yanzhengma($x,$y){
- //創建一個畫布x表示橫座標,y表示縱座標
- $this->img=imagecreatetruecolor($x,$y);//創建畫布,返回畫布句柄
- $rand = strlen($this->str)-2;
- $rand = $rand/2;//中文佔2個字節
- $text_color=imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));//隨機創建文本的顏色
- $text_color2=imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));//隨機創建背景的顏色
- $text='';
- for($i=0;$i<$this->geshu;$i++){
- $rand=mt_rand(0,$rand);//得到驗證碼
- $text=$text.substr($this->str,$rand*2,2);
- }
- $text=iconv('gb2312', 'UTF-8', $text);//必須轉換才能用
- imagefill($this->img, 0, 0, $text_color2);//填充背景
- imagettftext ($this->img,20,1,10,30,$text_color,"simkai.ttf",$text);//這個函數用於輸出中文
- //imagestring($img, 30, 40, 40, $text, $text_color);該函數只能用於英文數字
- imagepng($this->img);//顯示圖片
- return $text;//返回驗證碼,用於以後session
- }
- public function destory(){
- imagedestroy($this->img);//一定要關閉資源
- }
- }
- $img= new yanzhengma(5);
- $text=$img->yanzhengma(200,40);
- file_put_contents('1.txt', $text) ;
- $img->destory();
- ?>