您的位置:首页 > 编程语言 > PHP开发

PHP5中图片验证码的制作

2012-02-15 18:11 218 查看
PHP5中图片验证码的制作(上)

1、启用PHP中GD库

GD库提供了一系列用来处理图片的API,使用GD库可以处理图片,或者生成图片。 在网站上GD库通常用来生成缩略图或者用来对图片加水印或者对网站数据生成报表。

通过PHP.ini 启用GD库

extension=php_gd2.dll

2、部分GD库函数的介绍

(1) imagecreatetruecolor 新建一个真彩色图像

imagecreatetruecolor ( int x_size, int y_size ) // x就是宽 ,y就是高

(2)imagecolorallocate 为一幅图像分配颜色(调色板)

imagecolorallocate ( resource image, int red, int green, int blue )

(3)imagestring 绘图函数

imagestring ( resource image, font, int x, int y, 内容 , 颜色 )

3、学习:随机函数,十六进制函数

(1)rand 随机函数

rand ( [int min, int max] )

rand (1,4) 随机 1-4 之间的数

(2)dechex 十进制转换为十六进制

dechex ( 十进制数 )

十六进制 1 ~ f

4、GD+SESSION制作PHP验证码

<?php

session_start();

for($i=0;$i<4;$i++){//生成4位随机数

$rand.=dechex(rand(1,15));

}

$_SESSION[checkpic]=$rand;//把验证码存入session中

$im=imagecreatetruecolor(100,30);//创建一个图片

//设置图片颜色

$bg=imagecolorallocate($im,0,0,0);//第一次使用这个函数就是背景颜色

$te=imagecolorallocate($im,255,255,255);

//把字符卸载图片左上角

imagestring($im,rand(1,6),25,10,$rand,$te);

//输出图像

header("Content-type: image/jpeg");

imagejpeg($im);

?>

PHP5中图片验证码的制作(下)

1、image与header输出的介绍

PHP的HEADER是定义头的动作,新PHP5中支持三种类型:

Content-Type: xxxx/yyyy

Location: xxxx:yyyy/zzzz

Status: nnn xxxxxx

GD库中有对应的image类型

imagejpeg(*) imagegif(*) imagepng(*) ……

2、imageline 与 imagesetpixel 函数

imageline 画线函数

imageline ( resource image, int x1, int y1, int x2, int y2, int color )

imagesetpixel 画点函数

imagesetpixel ( resource image, int x, int y, int color )

3、imagettftext函数调用字体写入文字

imagettftext 带字体的写入函数

imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )

4、PHP验证码插入中文的方法

iconv("gb2312","UTF-8","新年快乐!"); //首先要将文字转换成UTF8格式

然后使用imagettftext 调用一种字体,再将转换好的UTF8格式的中文写入图片中!

<?php

session_start();

for($i=0;$i<4;$i++){//生成4位随机数

$rand.=dechex(rand(1,15));

}

$_SESSION[checkpic]=$rand;

$im=imagecreatetruecolor(100,30);//创建一个图片

//设置图片颜色

$bg=imagecolorallocate($im,0,0,0);//第一次使用这个函数就是背景颜色

$te=imagecolorallocate($im,255,255,255);

for($i=0;$i<3;$i++){//制造直线干扰

$te2=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));

imageline($im,0,rand(0,30),100,30,$te2);

}

for($i=0;$i<100;$i++){//制造噪点干扰

imagesetpixel($im,rand()%100,rand()%30,$te2);

}

$str=iconv("gbk","UTF-8","新年快乐");//设置字符编码

imagettftext($im,12,3,20,20,$te,'SIMLI.TTF',$str);//把中文写到图片上

//把字符卸载图片左上角

//imagestring($im,rand(1,6),25,10,$rand,$te);

//输出图像

header("Content-type: image/jpeg");

imagejpeg($im);

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: