PHP学习笔记(5)GD库画验证码

 1 <?php 
 2    header("content-type:image/png");
 3    $width = 500;
 4    $height = 500;
 5    $img = imagecreatetruecolor($width, $height);
 6    $string = "hello";
 7    //7种颜色,存入数组
 8    $red = imagecolorallocate($img, 255, 0, 0);
 9    $white = imagecolorallocate($img, 255, 255, 255);
10    $green = imagecolorallocate($img, 0, 255, 0);
11    $blue = imagecolorallocate($img, 0, 0, 255);
12    $aaa = imagecolorallocate($img, 255, 255, 0);
13    $bbb = imagecolorallocate($img, 0, 255, 255);
14    $ccc = imagecolorallocate($img, 255, 0, 255);
15    $colors = array($white,$red,$green,$blue,$aaa,$bbb,$ccc);
16    //画点
17    for ($i=0; $i < 1000; $i++) { 
18       imagesetpixel($img, mt_rand(0,$width), mt_rand(0,$height), $colors[mt_rand(0,6)]);
19    }
20    //划线
21    for ($i=0; $i < 200; $i++) { 
22       imageline($img, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $colors[mt_rand(0,6)]);
23    }
24    //生成4位验证码
25    $a1 = range(0, 9);
26    $a2 = range(a, z);
27    $a3 = range(A, Z);
28    $a4 = array_merge($a1,$a2,$a3);
29    $num = 4;
30    $fontsize = 60;
31    for ($i=0; $i < 4; $i++) { 
32       imagettftext($img, $fontsize, mt_rand(-45,45), $width/$num*$i+$fontsize, $height/2, $colors[mt_rand(0,6)], "Fonts/msyh.ttf", $a4[mt_rand(0,61)]);
33    }
34 
35    imagepng($img);
36  ?>

------------------------------------------------------------------------------- -----------------------------------------------------------------------------

下面的小一点:

 1 <?php 
 2    header("content-type:image/png");
 3    $width = 110;
 4    $height = 40;
 5    $img = imagecreatetruecolor($width, $height);
 6    $string = "hello";
 7    //7种颜色,存入数组
 8    $red = imagecolorallocate($img, 255, 0, 0);
 9    $white = imagecolorallocate($img, 255, 255, 255);
10    $green = imagecolorallocate($img, 0, 255, 0);
11    $blue = imagecolorallocate($img, 0, 0, 255);
12    $aaa = imagecolorallocate($img, 255, 255, 0);
13    $bbb = imagecolorallocate($img, 0, 255, 255);
14    $ccc = imagecolorallocate($img, 255, 0, 255);
15    $colors = array($white,$red,$green,$blue,$aaa,$bbb,$ccc);
16    //画点
17    for ($i=0; $i < 10; $i++) { 
18       imagesetpixel($img, mt_rand(0,$width), mt_rand(0,$height), $colors[mt_rand(0,6)]);
19    }
20    //划线
21    for ($i=0; $i < 4; $i++) { 
22       imageline($img, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $colors[mt_rand(0,6)]);
23    }
24    //生成4位验证码
25    $a1 = range(0, 9);
26    $a2 = range(a, z);
27    $a3 = range(A, Z);
28    $a4 = array_merge($a1,$a2,$a3);
29    $num = 4;
30    $fontsize = 20;
31    for ($i=0; $i < 4; $i++) { 
32       imagettftext($img, $fontsize, mt_rand(-45,45), $width/$num*$i+5, 30, $colors[mt_rand(0,6)], "Fonts/msyh.ttf", $a4[mt_rand(0,61)]);
33    }
34    imagepng($img);
35  ?>
原文地址:https://www.cnblogs.com/Jacklovely/p/6047038.html