应用PHP GD库中图像处理函数制作验证码

<?php 
	//开启session,之后会把验证码存入session,然后在后端与用户输入的验证码对比
	session_start();
	//新建一个真彩色图像
	$image=imagecreatetruecolor(100, 30);
	//定义白色
	$bgcolor=imagecolorallocate($image, 255, 255, 255);
	//填充颜色
	imagefill($image,0,0,$bgcolor);
	//验证码字符串
	$verify_str='';
	//循环产生四位字符
	for ($i=0; $i < 4; $i++) { 
		//设置字体
		$font='img/msyh.ttc';
		$fontsize=16;
		//随机颜色
		$fontcolor=imagecolorallocate($image, mt_rand(0,120), mt_rand(0,120), mt_rand(0,120));
		$contentstr='23456789acefghijkmpqrstvwxyz';
		//截取字符
		$fontcontent=substr($contentstr,mt_rand(0,strlen($contentstr)-1),1);
		$verify_str.=$fontcontent;
		//随机位置
		$x=($i*100/4)+mt_rand(5,10);
		$y=mt_rand(20,25);
		//将文字写进图中
		imagettftext($image, $fontsize, mt_rand(-30,30), $x, $y, $fontcolor, $font, $fontcontent);
	}

	//中文验证码
	/*for ($i=0; $i < 4; $i++) {
		$font='img/msyh.ttc'; 
		$fontsize=10;
		$fontcolor=imagecolorallocate($image, mt_rand(0,120), mt_rand(0,120), mt_rand(0,120));	
		$contentstr='这是一段话';
		$fontcontent=mb_substr($contentstr,mt_rand(0,strlen($contentstr)/3-1),1,"utf-8");
		$verify_str.=$fontcontent;
		$x=($i*100/4)+mt_rand(5,10);
		$y=mt_rand(20,25);
		imagettftext($image, $fontsize, mt_rand(-30,30), $x, $y, $fontcolor, $font, $fontcontent);
	}*/

	//把字符串存入session
	$_SESSION['verify']=$verify_str;
	//制作干扰项 200个点  三条线
	for ($i=0; $i <200 ; $i++) { 
		$pointcolor=imagecolorallocate($image,mt_rand(50,200),mt_rand(50,200),mt_rand(50,200));
		imagesetpixel($image, mt_rand(1,99), mt_rand(1,29), $pointcolor);
	}
	for ($i=0; $i < 3; $i++) { 
		$linecolor=imagecolorallocate($image, mt_rand(80,220), mt_rand(80,220), mt_rand(80,220));
		imageline($image, mt_rand(1,99), mt_rand(1,29), mt_rand(1,99), mt_rand(1,29), $linecolor);
	}
	//设置头信息,告诉浏览器输出的内容是图像
	header('Content-type:image/png');
	//输出图片
	imagepng($image);
	//销毁图像  释放与 image 关联的内存。
	imagedestroy($image);
 ?>



效果展示:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值