Home >Backend Development >PHP Problem >How to generate verification code image in php

How to generate verification code image in php

autoload
autoloadOriginal
2021-03-17 17:46:422881browse

1.获取生成验证码字体:

                                在php文件路径新建一个fonts文件夹,里面有字体文件。

     //判定字体资源
      if(empty($fonts))
         $fonts="arial.ttf";

      //确认字体路径
      $fonts=__DIR__."/fonts/".$fonts;
      $fonts=str_replace("/","\\",$fonts);

2.制作画布,随机分配背景色

$img=imagecreatetruecolor($width,$height);
      
$bg_color=imagecolordeallocate($img,mt_rand(200,255),mt_rand(200,250));
imagefilter($img,0,0,$bg_color);

3.增加干扰点、线

//增加干扰点:*
      for($i = 0;$i < 50;$i++)
      {
      //随机颜色
       $dots_color = imagecolorallocate($img, mt_rand(140,190), mt_rand(140,190), mt_rand(140,190));
      //使用*号作为干扰点
       imagestring($img, mt_rand(1,5), mt_rand(0,$width), mt_rand(0,$height), &#39;*&#39;, $dots_color);
      }
     //增加干扰线
     for($j = 0;$j < 10;$j++)
     {
      //随机线段颜色
      $line_color = imagecolorallocate($img, mt_rand(80,130), mt_rand(80,130), mt_rand(80,130));
      //随机线段
      imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$line_color);
     }

4.将验证码放入图片

 $captcha=array(3,4,&#39;a&#39;,&#39;i&#39;);//可以自己使用写一个方法生成数组;
 $length=sizeof($captcha);
   for($i = 0;$i < $length;$i++){
   //给每个字符分配不同颜色
   $c_color = imagecolorallocate($img, mt_rand(0,60), mt_rand(0,60), mt_rand(0,60));
   
   //增加字体空间、大小、角度显示
imagettftext($img,mt_rand(15,25),mt_rand(-45,45),$width/($length+1)*($i+1),mt_rand(25,$height-25),$c_color,$fonts,$captcha[$i]);
  }

5.保存图片

imagejpeg($img,"test.jpg",100);

推荐:php视频教程 php教程

The above is the detailed content of How to generate verification code image in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn