PHP GD库绘制验证码

2018-05-14  本文已影响7人  大大哟nice

PHP GD库绘制简单验证码

程序代码:

<?php

//简单使用GD绘制验证码   需要加载PHP_gd2.dll文件

// session_start();

/*

 *功能:给出随机长度的字符

 *参数:

 *            $len -给定字符串的长度

 *输出:随机给定长度的字符串

 * */

header ( "content-type:image/png");  //定义文件的类型

function random($len) {

    $srcstr="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

         $strs= "";

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

                   $strs.= $srcstr [mt_rand ( 0, 60 )]; //mt_rand生成更好的随机数

         }

         //      return strtoupper ( $strs );             //将字符串转化为大写字母

         return  $strs ;

}

$str = random ( 4 );

$width = 120;

$height = 35;

$image = imagecreate ( $width, $height );                        //创建图像

$back = imagecolorallocate ( $image, 0xFF,0xFF, 0xFF );        //设置背景颜色

$font = imagecolorallocate ( $image, 287,330, 347 );             //绘制模糊作用点

$font_color = imagecolorallocate ( $image,

mt_rand ( 50, 120 ), mt_rand ( 50, 120 ), mt_rand ( 50, 120 ) ); //设置字体颜色

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

         //画一个单一像素

         imagesetpixel( $image, mt_rand ( 0, $width ), mt_rand ( 0, $height ), imagecolorallocate ($image, mt_rand ( 1, 255 ), mt_rand ( 1, 255 ), mt_rand ( 1, 255 ) ) );

}

$font_file =$_SERVER['DOCUMENT_ROOT'].'arial.ttf'; //获取字体的文件位置

//设置字体的位置和颜色

imagettftext($image, mt_rand(15,28),mt_rand(-30,30), 5, 30, $font_color, $font_file, substr($str,0,1));

imagettftext($image, mt_rand(15,28),mt_rand(-30,30), 35, 30, $font_color, $font_file, substr($str,1,1));

imagettftext($image, mt_rand(15,28),mt_rand(-30,30), 65, 30, $font_color, $font_file, substr($str,2,1));

imagettftext($image, mt_rand(15,28),mt_rand(-30,30), 95, 30, $font_color, $font_file, substr($str,3,1));

imagerectangle($image, 0, 0, $width-1,

$height-1, $font); //画一个矩形

imagepng($image);                 //显示

imagedestroy($image);          //结束

?>

功能截图:

image
上一篇 下一篇

猜你喜欢

热点阅读