<?php
class Imagecode{
private $width,$height,$str;//宽、高、随机字符
function __construct($width=120,$height=30,$str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{
$this->width=$width;
$this->height=$height;
$this->str=$str;
}
function creatimg(){
return imagecreate($this->width,$this->height);
}
function random($len=4) //随机数
{
$str = substr(str_shuffle($this->str),0,$len);//取4个字符
$this->strout=$str;
}
function setbackground($img){
$background_color=imagecolorallocate($img,255,255, 255);
$border_color=imagecolorallocate($img, 41,163,238);
$color = ImageColorAllocate($img, 0,0,0);
imagefill($img,0, 0, $background_color);//背景、白色
imagerectangle($img, 0, 0, $this->width-1, $this->height-1, $border_color);//边框
$w=$this->width/2-18;
$h=$this->height/2-7;
imagestring($img,12,$w,$h,$this->strout, $border_color);//字位置
for($i=1;$i<3;$i++){
//$line_color = imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));//随机颜色
//imageline($img,1,$i,47,$i,$line_color);//固定 位置画线
//imagesetpixel($img,mt_rand(0, $width) ,mt_rand(0,$height), $line_color); //画点
imageline($img,rand($w,30),rand($h,21),rand($w+20,50),rand($h,21),$border_color); //随机位置画线
}
}
function imgout(){
$img=$this->creatimg();
$this->random();
$this->setbackground($img);
imagepng($img);
imagedestroy($img);
$_SESSION["code"] = $this->strout ;
session_destroy();
}
}
@header("Content-Type:image/png");
session_start();
$img=new Imagecode(50,20);
$img->imgout();
?>
PHP图片验证码
效果: