- 开发无止境 -
Data: 2015-04-17 21:54:40Form: JournalClick: 8
转载路径:http://hi.baidu.com/asdasd_cn/item/62977d1e26ca36e85e53b142
生成验证码图片的两个函数
第一个是用imagestring
bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )
imagestring() 用 col 颜色将字符串 s 画到 image 所代表的图像的 x,y 坐标处(这是字符串左上角坐标,整幅图像的左上角为 0,0)。如果 font 是 1,2,3,4 或 5,则使用内置字体。
public function captcha1() {
Header("Content-type: image/PNG");
$rand.=dechex(rand(0,15));
$im = imagecreate(100,50);
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
$gray = ImageColorAllocate($im, 200,200,200);
$te=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagefill($im,0,0,$gray);
while(($rand=rand()%100000)<10000);
imagestring($im, 5, 30, 20, $rand, $te);
$randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($im, rand()%100 , rand()%50 , $randcolor);
imageline($im,0,rand(0,100),100,rand(0,15),$randcolor);
imageline($im,0,rand(0,100),100,rand(0,15),$randcolor);
imageline($im,0,rand(0,100),100,rand(0,15),$randcolor);
第二个函数可根据根据字体库设置大小Linux端的注意路径
imagefttext — 使用 FreeType 2 字体将文本写入图像
array imagefttext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text [, array $extrainfo ] )
function captcha2($num=4,$size=20, $width=0,$height=0){
!$width && $width = $num*$size*4/5+5;
!$height && $height = $size + 10;
$str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW";
for ($i=0; $i<$num; $i++){
$code.= $str[mt_rand(0, strlen($str)-1)];
$im = imagecreatetruecolor($width,$height);
$back_color = imagecolorallocate($im, 235, 236, 237);
$boer_color = imagecolorallocate($im, 118, 151, 199);
$text_color = imagecolorallocate($im, mt_rand(0,200), mt_rand(0,120), mt_rand(0,120));
imagefilledrectangle($im,0,0,$width,$height,$back_color);
imagerectangle($im,0,0,$width-1,$height-1,$boer_color);
$font_color = imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
imagearc($im,mt_rand(-$width,$width),mt_rand(-$height,$height),mt_rand(30,$width*2),mt_rand(20,$height*2),mt_rand(0,360),mt_rand(0,360),$font_color);
$font_color = imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$font_color);
@imagefttext($im, $size , 0, 5, $size+3, $text_color, 'c://WINDOWS//Fonts//simsun.ttc',$code);
header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");
header("Content-type: image/png");
附:
Linux-debian 字体默认路径:/usr/share/fonts/truetype/ttf-dejavu/
考虑到程序的可移植性,在程序目录中新建字体目录fonts来使用。