PHP 创建扭曲英文验证码

<?php 
/*
 * 利用GD库的相关概念,创建一个扭曲的验证码。
 * */
class image{
	public static function code(){
		$str = 'ABCDEFGHJKMNPQRTUVWXYZabcdefhjkmnpqrtuvwxyz234678';
		$code = substr(str_shuffle($str), 0,5);
		//创建画布
		$src = imagecreatetruecolor(100, 50);
		$dst = imagecreatetruecolor(100, 50);
		//创建颜色
		$sgray = imagecolorallocate($src, 200, 200, 200); 
		$dgray = imagecolorallocate($dst, 200, 200, 200); 
		$randcolor = imagecolorallocate($src, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
		//填充背景
		imagefill($src, 0, 0, $sgray);
		imagefill($dst, 0, 0, $dgray);
		//写字
		imagestring($src, 10, 30, 15, $code, $randcolor);
		for ($i=0; $i < 100; $i++) {
			//第四个参数,复制到 dst 的 Y 值非常重要 
			//根据正弦曲线来计算波动量
			$offset = 3; //最大波动3PX
			$round = 2; //扭动2个周期
			//根据正弦曲线设置偏移量
			$posY = round(sin(($round * 2 * M_PI / 60) * $i) * $offset);
			imagecopy($dst, $src, $i, $posY, $i, 0, 1, 50);
		}
		//保存
		header('content-type: image/jpeg');
		imagejpeg($dst);
		//销毁
		imagedestroy($dst);
	}
}
image::code();

效果图:

 

猜你喜欢

转载自onestopweb.iteye.com/blog/2340923