/** * 生成验证码,使用TTF字体 * @param $font * @param $img_width * @param $img_height * @return unknown_type */ static function verify_ttf($font, $width = 180, $height = 130) { if (empty($_SESSION)) { session_start(); } $length = 4; $code = RandomKey::getChineseCharacter(4); $width = $length * 45 > $width ? $length * 45 : $width; $_SESSION['authcode'] = md5($code); $im = imagecreatetruecolor($width, $height); $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色 $bkcolor = imagecolorallocate($im, 250, 250, 250); imagefill($im, 0, 0, $bkcolor); imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor); // 干扰 for ($i = 0; $i < 15; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor); } for ($i = 0; $i < 255; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor); } for ($i = 0; $i < $length; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); //这样保证随机出来的颜色较深。 $codex = self::msubstr($code, $i, 1); imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $font, $codex); } Header("Content-type: image/png"); //告诉浏览器,下面的数据是图片 ImagePng($im); //生成png格式 ImageDestroy($im); }
/** * 生成汉字验证码 * @param $font * @param $width * @param $height * @return array */ static function verifycode_chinese($font, $width = 180, $height = 60) { $length = 4; $angle = 45; $width = $length * 45 > $width ? $length * 45 : $width; $im = imagecreatetruecolor($width, $height); $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色 $bkcolor = imagecolorallocate($im, 250, 250, 250); imagefill($im, 0, 0, $bkcolor); imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor); // 干扰 for ($i = 0; $i < 5; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor); } for ($i = 0; $i < 255; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor); } $code = ''; for ($i = 0; $i < $length; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); //这样保证随机出来的颜色较深。 $codex = RandomKey::getChineseCharacter(1); $code .= $codex; @imagettftext($im, mt_rand(16, 20), mt_rand(-$angle, $angle), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $font, $codex); } ob_start(); ImagePng($im); $data = ob_get_clean(); ImageDestroy($im); return array('code' => $code, 'image' => $data); }