一、简单验证码生成
/*
验证码
写字---> imagestring
*/
1、造画布
$im = imagecreatetruecolor(50,25);
// 不填充时猜猜画布是什么颜色的?
2、造颜料准备写字
$red = imagecolorallocate($im,255,0,0);
3、写字
/*
imagestring --- 水平地画一行字符串
bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )
参数:
画布资源
字体大小(1-5选择)
字符最左上角的x坐标,y坐标
要写的字符串
颜色
*/
$str = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ23456789';
$s = substr(str_shuffle($str),0,4);
//imagestring($im,5,0,0,'hello',$red); //hello的红字效果
imagestring($im,5,0,0,$s,$red);
header('content-type:image/png');
imagepng($im);
二、复杂一点的验证码(有随机干扰线+随机颜色)
1、造画布
$im = imagecreatetruecolor(50,25);
2、造颜料准备写字
$red = imagecolorallocate($im,255,0,0);
// 浅色背景
$gray = imagecolorallocate($im,220,220,220);
// 随机颜色
//$randcolor = imagecolorallocate($im,mt_rand(150,255),mt_rand(150,255),mt_rand(150,255));
$randcolor = imagecolorallocate($im,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150));
// 随机颜色干扰线
$linecolor1 = imagecolorallocate($im,mt_rand(100,150),mt_rand(100,150),mt_rand(100,150));
$linecolor2 = imagecolorallocate($im,mt_rand(100,150),mt_rand(100,150),mt_rand(100,150));
$linecolor3 = imagecolorallocate($im,mt_rand(100,150),mt_rand(100,150),mt_rand(100,150));
// 填充背景
imagefill($im,0,0,$gray);
// 画出干扰线
imageline($im,0,mt_rand(0,25),50,mt_rand(0,25),$linecolor1);
imageline($im,0,mt_rand(0,25),50,mt_rand(0,25),$linecolor2);
imageline($im,0,mt_rand(0,25),50,mt_rand(0,25),$linecolor3);
3、写字
/*
imagestring --- 水平地画一行字符串
bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )
参数:
画布资源
字体大小(1-5选择)
字符最左上角的x坐标,y坐标
要写的字符串
颜色
*/
$str = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ23456789';
$s = substr(str_shuffle($str),0,4);
//imagestring($im,5,0,0,'hello',$red); //hello的红字效果
imagestring($im,5,8,5,$s,$randcolor);
header('content-type:image/png');
imagepng($im);
三、验证码字符串的扭曲(正弦曲线函数,弧度函数)
思路图
代码
class image {
public static function code() {
$str = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ23456789';
$code = substr(str_shuffle($str),0,5);
// 2块画布
$src = imagecreatetruecolor(60,25);
$dst = imagecreatetruecolor(60,25);
// 灰色背景
$sgray = imagecolorallocate($src,200,200,200);
$dgray = imagecolorallocate($src,200,200,200);
// 蓝色
$sblue = imagecolorallocate($src,0,0,255);
imagefill($src,0,0,$sgray);
imagefill($dst,0,0,$dgray);
// 写字
imagestring($src,5,5,4,$code,$sblue);
// 扭曲的关键
for($i=0;$i<60;$i++) {
// 根据正弦曲线计算上下波动的posY
$offset = 3; // 最大波动几个像素
$round = 2; // 扭2个周期,即4PI
$posY = round(sin($i * $round * 2 * M_PI / 60) * $offset); // 根据正弦曲线,计算偏移量
imagecopy($dst,$src,$i,$posY,$i,0,1,25);
}
// 输出
header('content-type:image/jpeg');
imagejpeg($dst);
}
}
image::code();