PHP使用GD库画数字验证码

本文介绍如何使用PHP和GD库创建包含文字、干扰线及干扰点的图片验证码。通过设置字体颜色、背景颜色等参数,生成具有一定复杂度的验证码图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 使用前查看一下php.ini中extension=gd2前的分号去掉了没,默认是去掉的。修改php.ini后需要重启Apache服务器修改才能生效。
  • 直接看代码吧
    header("Content-type:text/html;charset=UTF-8");
    $image = imagecreatetruecolor(120,40);
    $font = 'C:/Windows/Fonts/simhei.ttf';
    $bg = imagecolorallocate($image,255,255,0);
    // 填充
    imagefill($image,0,0,$bg);
    // 绘制干扰线
    for($i=0;$i<5;$i++) {
    $lineColor = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
    imageline($image,rand(0,120),rand(0,40),rand(0,100),rand(0,20),$lineColor);
    }
    // 绘制干扰点
    for($i=0; $i<100; $i++) {
    $pointColor = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
    imagesetpixel($image,rand(1,119),rand(1,39),$pointColor);
    }
    // 添加验证码
    for($i=0; $i<4; $i++) {
    $textColor = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
    $m = rand(0,9);
    imagettftext($image,20,rand(30,-30),($i*20+10),rand(20,30),$textColor,$font,$m);
    }
    header("Content-type:image/jpeg");
    imagejpeg($image);
    imagedestroy($image);

    效果如图:
    这里写图片描述
    如果上述代码中有不明白的函数请去http://php.net/manual/zh/上搜索。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值