<?php /* * 绘制干扰点 */ $width =60; $height=25; //图片句柄 $image = imagecreate($width, $height); //背景颜色 $image_bgcolor = imagecolorallocate($image, 255, 255, 255); //$边框颜色 $image_bolorcolor = imagecolorallocate($image, 0, 0, 0); //绘制边框 imagerectangle($image, 0, 0, $width-1, $height-1, $image_bolorcolor); //设置干扰点个数 $num_distrub_points =200; for ($i = 0; $i < $num_distrub_points; $i++) { //随机设置干扰点颜色 $point_color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255)); //干扰点的位置 $point_x = rand(2, $width-2); $point_y = rand(2, $height-2); //绘制干扰点 imagesetpixel($image, $point_x, $point_y, $point_color); } header("content-type:image/png"); imagepng($image); imagedestroy($image); ?> |
一个完整的验证码
<?php /** * 创建一个完整版的验证码 */ function createCheckCode($width=60,$height=25,$num_code=5,$num_distrub_points=200){ //创建画布 $image = imagecreate($width, $height); //绘制背景颜色 $image_bgcolor = imagecolorallocate($image, 255, 255, 255); //会孩子边框颜色 $image_border_color = imagecolorallocate($image, 0, 0, 0); //绘制边框 imagerectangle($image, 0, 0, $width-1, $height-1, $image_border_color); /* * 产生随机码 */ $rand_num = rand(); $str = md5($rand_num); //将随机码全部换成大写 $str_code = strtoupper(substr($str, 0,$num_code)); /* * 绘制随机码(添加到画布上) */ for ($i = 0; $i < $num_code; $i++) { //每个随机码的颜色 $str_color = imagecolorallocate($image, rand(0,255), rand(0,255), rand(0,255)); //随机码的字体大小 $font_size =5; //随机码在画布中出现的位置 $str_x = floor(($width/$num_code)*$i)+rand(0, 5); $str_y = rand(2, $height-15); //将随机码添加到画布中 imagechar($image, $font_size, $str_x, $str_y, $str_code[$i], $str_color); /* * 绘制干扰点 */ } for ($i = 0; $i < $num_distrub_points; $i++) { //每个干扰点的颜色 $point_color = imagecolorallocate($image, rand(0,100), rand(0,100), rand(0,100)); $point_x = rand(2, $width-2); $point_y = rand(2, $height-2);
imagesetpixel($image, $point_x, $point_y, $point_color); } header("content-type:image/png"); //输出画布图片 imagepng($image); imagedestroy($image); } createCheckCode(); ?> |