PHP生成图片验证码
分为两个方法函数
verifyCode = substr($verifyCode, 0, $length); return $this->verifyCode; } /** * todo:加入字符,生成图片,并加入干扰线,干扰素 * @param int $width 图片宽度 * @param int $height 图片高度 */ public function createImage($width = 80, $height = 30) { $verifyCode = $this->verifyCode; $image = imagecreatetruecolor($width, $height); //白色背景 $white = imagecolorallocate($image, 255, 255, 255); //字体颜色 $fontStyle = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));; imagefill($image, 0, 0, $white); // 使用默认字体,无法修改文字大小 // imagestring($image, 5, 10, 10, $verifyCode, $fontStyle); // 导入自定义字体,修改文字大小 imagettftext($image, 24, 0, 5, 20, $fontStyle, '../microsofthimalaya.ttf', $verifyCode); //加入干扰点 for ($i = 0; $i < 80; $i++) { $color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255)); imagesetpixel($image, rand(0, $width), rand(0, $height), $color); } //干扰线 for ($i = 0; $i < 5; $i++) { $color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255)); imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color); } //输出图片 header("Content-type: image/png"); imagepng($image); //释放资源 imagedestroy($image); }}?>
实例
$VerifyImage = new VerifyImage();$code = $VerifyImage->createCode();$_SESSION['$VerifyCode'] = $code;$VerifyImage->createImage();