/**
- * CaptchaImage() - 建立扭曲字元的驗證碼圖片
- * $session_name string 驗證碼圖片建立時所需產生Session的變數名
- * $width int 驗證圖片的寬度,預設120,註:圖片高度與寬度比例相對固定
- * $noise int 幹擾素的點數,預設0
- * $disturb int 幹擾字元個數,預設0
- * $curve bool 是否增加幹擾曲線,預設ture
- * */
- function CaptchaImage($session_name = '', $width = 120, $noise = 0, $disturb = 0, $curve = true){
- $im_x = $width;
- $im_y = ceil(0.25 * $width);
- $im = imagecreatetruecolor($im_x, $im_y);
- $text_c = ImageColorAllocate($im, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
- $gray_rand = mt_rand(160, 220);
- $buttum_c = ImageColorAllocate($im, $gray_rand, $gray_rand, $gray_rand);
- imagefill($im, 0, 0, $buttum_c);
session_start();
- $text = '';
- $characters = 'ABCEFGHJKLMNPQRSTUVWXYZ';
- for($i = 0, $len = strlen($characters); $i < 4; $i++){
- $text .= $characters{rand(0, $len - 1)};
- if(isset($session_name{0}) && session_start()){
- $_SESSION[$session_name] = $text;
- $_SESSION['CaptchaSessionTime'] = time();
- }
- }
$font = 'arial.ttf';
- $size = floor(0.2 * $width);
$ttfbox = imagettfbbox($size, 0, $font, $text);
- $text_width = abs($ttfbox[2] - $ttfbox[0]);
- $side = floor(($im_x - $text_width) / 2);
$array = array(-1, 1);
- for ($i = 0; $i < strlen($text); $i++){
- $p = array_rand($array);
- $an = $array[$p] * mt_rand(5, 10); // 字元傾斜角度
- imagettftext($im, $size, $an, $side + $i * ($size - 1), $im_y - 3, $text_c, $font, $text{$i});
- }
$distortion_im = imagecreatetruecolor ($im_x, $im_y);
- imagefill($distortion_im, 0, 0, $buttum_c);
- $distortion = floor(0.04 * $width); // 扭曲程度
- for ($i = 0; $i < $im_x; $i++){
- for ($j = 0; $j < $im_y; $j++){
- $rgb = imagecolorat($im, $i , $j);
- if( (int)($i + sin($j / $im_y * 2 * M_PI) * $distortion) <= $im_x && (int)($i + sin($j / $im_y * 2 * M_PI) * $distortion) >= 0 ){
- imagesetpixel($distortion_im, (int)($i + sin($j / $im_y * 2 * M_PI - M_PI * 0.1) * $distortion) , $j, $rgb);
- }
- }
- }
if($disturb > 0){
- $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
- for($i = 0; $i < $disturb; $i++){
- imagestring($distortion_im, 3, mt_rand(-10, $im_x), mt_rand(-10, $im_y), $chars[mt_rand(0, 35)], $text_c);
- }
- }
//加入幹擾象素;
- if($noise > 0){
- for($i = 0; $i < $noise; $i++){
- $randcolor = ImageColorallocate($distortion_im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
- imagesetpixel($distortion_im, mt_rand()%$im_x , mt_rand()%$im_y , $randcolor);
- }
- }
// 加幹擾曲線
- if($curve){
- $rand = mt_rand(5, 30);
- $rand1 = mt_rand(15, 25);
- $rand2 = mt_rand(5, 10);
- for ($yy = $rand; $yy <= $rand + 2; $yy++){
- for ($px = -60; $px <= 60; $px++){
- $x = $px / $rand1;
- $y = ($x != 0) ? sin($x) : $y;
- $py = $y * $rand2;
- imagesetpixel($distortion_im, $px + 60, $py + $yy, $text_c);
- }
- }
- }
//設定檔案頭;
- Header("Content-type: image/JPEG");
//以PNG格式將映像輸出到瀏覽器或檔案;
- ImagePNG($distortion_im);
//銷毀一映像,釋放與image關聯的記憶體;
- ImageDestroy($distortion_im);
- ImageDestroy($im);
- }
CaptchaImage('code', 100); //產生一張圖片 並將隨機數字存放到key為code的session中
複製代碼 |