PHP学习--验证码

在正式制作验证码之前要先补充点知识,PHP使用GD2函数库实现对各种图形图像的处理,所以我们制作验证码主要要使用到一些GD2函数库里的一些函数:

imagecreatetruecolor($width,$height)函数,主要用于创建画布,有2个参数width和height是必选的,代表你所要创建的画布的长和宽;

imagecolorallocate($image, $red, $green, $blue)函数,主要用于填充图像,第1个参数是你所创建的图像的标识符,后面3个参数是颜色的RGB设置;

imagefill($image, $x, $y, $color)函数,第一个函数是你创建的图像标识符,第2、3个参数$x、$y是左上角坐标,最后一个参数是你要填充颜色;

imagestring($image, $font, $x, $y, $string, $color)函数设置文字,且imagestring()函数如果直接绘制中文字符串会出现乱码,如果要绘制中文字符串可以使用imagettftext()函数;

imagepng($image[,$filename])函数以phg格式将图像输出到浏览器或者保存为文件,第1个参数为你创建的图像标识号,第2个参数为可选参数,你要保存文件的文件名;

imagesetpixel($image, $x, $y, $color)函数画单个像素点;

imageline($image, $x1, $y1, $x2, $y2, $color)函数画一条线段,$x1、$y1是线段是左上角坐标,$x2、$y2是线段的右下角坐标。

代码主要如下:

<?php
	//创建画布
	$img = imagecreatetruecolor(100, 50);
	//创建颜色
	$black = imagecolorallocate($img, 0x00, 0x00, 0x00);
	$green = imagecolorallocate($img, 0x00, 0xFF, 0x00);
	$white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF);
	//画布填充颜色
	imagefill($img, 0, 0, $white);//背景为白色
	//生成随机验证码
	$code = make(5);
	//设置文字
	imagestring($img, 5, 10, 10, $code, $black);//黑字
	//加入噪点干扰
	for ($i = 0; $i <300; $i++){
		imagesetpixel($img, rand(0, 100), rand(0, 100), $black);
		imagesetpixel($img, rand(0, 100), rand(0, 100), $green);
	}
	//加入线段干扰
	for ($n = 0; $n <=1; $n++){
		imageline($img, 0, rand(0, 40), 100, rand(0, 40), $black);
		imageline($img, 0, rand(0, 40), 100, rand(0, 40), $white);
	}
	//输出验证码
	header("content-type: image/png");//告诉浏览器这个文件是一个png图片
	imagepng($img);
	//销毁图片,释放内存
	imagedestroy($img);
	//生成随机验证码的函数
	function make($length){
		$code = 'abcdefghijklmnopqrsruvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		//str_shuffle()函数用于打乱字符串
		return substr(str_shuffle($code), 0, $length);
	}
?>

实现效果如下图:

扫描二维码关注公众号,回复: 3845270 查看本文章

猜你喜欢

转载自blog.csdn.net/Cairo960918/article/details/83589143