整體的思路:
1谆沃、準備畫布
2钝凶、生成顏色
3、生成的字符范圍
4唁影、開始寫字
5耕陷、插入干擾線(點)
6、指定輸出的類型
7据沈、準備輸出圖片
8哟沫、銷毀
<?php
// 生成隨機驗證碼的方法
function verify($width = 100, $height = 40, $num = 5, $type = 3)
{
// 1、準備畫布
$image = imagecreatetruecolor($width, $height);
imagefilledrectangle($image, 0, 0, $width, $height, lightColor($image)); //給畫布填充一個淺色背景
// 2锌介、生成顏色
// 3嗜诀、需要什么字符
$string = '';
switch ($type) {
case 1: //0-9的數字
$str = '0123456789';
//str_shuffle($str); 隨機打亂$str
$string = substr(str_shuffle($str), 0, $num);
break;
case 2: //a-b的字母
$arr = range('a', 'z');
shuffle($arr);
$tmp = array_slice($arr, 0, $num);
$string = join('', $tmp);
break;
case 3: //0-9 a-z A-Z的隨機組合
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = substr(str_shuffle($str), 0, $num);
break;
}
// 4、開始寫字
for ($i = 0; $i < $num; $i++) {
$x = floor($width / $num) * $i;
$y = mt_rand(10, $height - 20);
imagechar($image, 5, $x, $y, $string[$i], deepColor($image));
}
// 5孔祸、插入干擾線(點)
for ($i = 0; $i < 5; $i++) {
imagearc($image, mt_rand(10, $width), mt_rand(10, $height), mt_rand(10, $width), mt_rand(10, $height), mt_rand(0, 10), mt_rand(0, 270), deepColor($image));
}
for ($i = 0; $i < 50; $i++) {
imagesetpixel($image, mt_rand(0, $width), mt_rand(10, $height), deepColor($image));
}
// 6隆敢、指定輸出的類型
header('Content-type:image/png');
// 7、準備輸出圖片
imagepng($image);
// 8融击、銷毀
imagedestroy($image);
return $string;
}
// 生成淺的顏色
function lightColor($image)
{
return imagecolorallocate($image, mt_rand(130, 255), mt_rand(130, 255), mt_rand(130, 255));
}
// 生成深色
function deepColor($image)
{
return imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
}
verify();