php 生成验证码(带旋转和干扰线条)

10 篇文章 0 订阅
6 篇文章 0 订阅

带旋转和干扰线条的验证码生成函数,代码如下:

<?php
	// 把字符串做出验证码图片
	// string $text,要处理的字符串
	// int $linect,需要混淆的线条个数
	// int $fontsize,字体大小,1到5
	// bool $rotate,是否旋转
	// array $textcol,字体颜色RGB值,array(R,G,B)
	// array $bgcol,背景色RGB值,array(R,G,B)
	function verifyCode($text, $linect=6, $fontsize=5, $rotate=array(-44,44), $textcol = array(255,0,0), $bgcol=array(255,255,255)){
		$len = strlen($text);
		$tximgw = imagefontwidth($fontsize);
		$tximgh = imagefontheight($fontsize);

		$imgof = $tximgw/2;
		$imgw = $len*($tximgw+$imgof);
		$imgh = $tximgh;
		
		$img = imagecreate($imgw, $imgh);

		imagefill($img, 0,0, imagecolorallocate($img, $bgcol[0], $bgcol[1], $bgcol[2]));
		
		// 输出字符
		for($i=0; $i<$len; ++$i){
			$char = $text[$i];
			$tximg = imagecreate($tximgw, $tximgh);
			$txbgcol = imagecolorallocate($tximg, $bgcol[0], $bgcol[1], $bgcol[2]);
			$txcol = imagecolorallocate($tximg, $textcol[0], $textcol[1], $textcol[2]);
			imagestring($tximg, $fontsize, 0, 0, $char, $txcol);
			$ag = $rotate?rand($rotate[0],$rotate[1]):0;
			
			// 旋转字符随机角度
			$oimg = imagerotate($tximg, $ag, $txbgcol);
			imagecopy($img, $oimg, $i*($tximgw+$imgof), 0 , 0 , 0 , imagesx($oimg) , imagesy($oimg));
			
			// 释放临时产生的图片资源
			imagedestroy($tximg);
			imagedestroy($oimg);
		}
		
		// 产生混淆的线条
		for($i=0; $i<$linect; ++$i){
			$x = rand(0, $imgw);
			$y = rand(0, $imgh);
			$x1 = rand(0, $imgw);
			$y1 = rand(0, $imgh);
			imageline ($img, $x, $y, $x1, $y1, imagecolorallocate($img, rand(0,255), rand(0,255), rand(0,255)));
		}
		return $img;
	}
	// 测试
	$text = 'HelloWorld';
	// 产生一个有5个混淆线条,字体为5,旋转角度在[-30,30]间的验证码
	$img = verifyCode($text, 5, 5, array(-30, 30));
	// 设置输出类型为png图片
	header("Content-type: image/png");
	// 输出
	imagepng($img);
	// 释放资源
	imagedestroy($img);
?>


效果如图:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RobinTang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值