php怎么生成验证码图片,php生成图片验证码

以下代码直接运行然后输出到html的img标签的src属性即可

验证码图片

php代码

//如果是在laravel框架中使用

ob_end_clean(); //不然刷新过快时会有乱码

//1.创建黑色画布

$image = imagecreatetruecolor(120, 40);

//2.为画布定义(背景)颜色

$bgcolor = imagecolorallocate($image, 255, 255, 255);

//3.填充颜色

imagefill($image, 0, 0, $bgcolor);

// 4.设置验证码内容

//4.1 随机字符池

$content = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789";

//4.1 创建一个变量存储产生的验证码数据,便于用户提交核对

$captcha = "";

for ($i = 0; $i < 4; $i++) {

// 字体大小

$fontsize = mt_rand(20,24);

// 字体颜色

$fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));

// 获取随机字符

$fontcontent = substr($content, mt_rand(0, strlen($content)-1), 1);

$captcha .= $fontcontent;

// 在图片中的坐标

$x = ($i * 108 / 4) + mt_rand(3, 12);

$y = mt_rand(24, 36);

// 填充内容到画布中

// imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor); //这种方法不能设置字体大小

//字体文件必须有

imagettftext( $image, $fontsize, mt_rand(0,16), $x, $y, $fontcolor, '/tmp/fonts/DejaVuSans-Bold.ttf', $fontcontent);

}

//验证码内容存入session

$_SESSION["captcha"] = $captcha;

$_SESSION["lower_captcha"] = strtolower($captcha);

$_SESSION["upper_captcha"] = strtoupper($captcha);

//4.3 设置背景干扰元素

for ($i = 0; $i < 255; $i++) {

$pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));

imagesetpixel($image, mt_rand(1, 119), mt_rand(1, 39), $pointcolor);

}

//4.4 设置干扰线

for ($i = 0; $i < 12; $i++) {

$linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));

imageline($image, mt_rand(1, 119), mt_rand(1, 39), mt_rand(1, 119), mt_rand(1, 39), $linecolor);

}

//5.向浏览器输出图片头信息

header('content-type:image/png');

//6.输出图片到浏览器

imagepng($image);

//7.销毁图片

imagedestroy($image);

在laravel框架中最好控制器类中加上析构函数

//销毁图片,防止乱码

public function __destruct()

{

imagedestroy($this->image);

exit();

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值