PHP生成简单验证码(例子)

来源:互联网 发布:在职软件工程硕士叫停 编辑:程序博客网 时间:2024/05/22 06:43

使用PHP生成最简单验证码的小例子

生成的验证码大概是这样:

验证码

生成验证码

<?php//创建图像$img = imagecreatetruecolor(60, 30);//设置颜色$black = imagecolorallocate($img, 0x00, 0x00, 0x00);$green = imagecolorallocate($img, 0x00, 0xFF, 0x00);$white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF);//填充背景颜色imagefill($img,0,0,$white);//生成随机的验证码$code = '';for($i = 0; $i < 4; $i++) {    $code .= rand(0, 9);}//将验证码添加到图片imagestring($img, 5, 10, 10, $code, $black);//加入噪点干扰for($i=0;$i<50;$i++) {    //在随机位置添加噪点    imagesetpixel($img, rand(0, 100) , rand(0, 100) , $black);    imagesetpixel($img, rand(0, 100) , rand(0, 100) , $green);}//输出验证码header("content-type: image/png");//生成验证码图片imagepng($img);//销毁图像imagedestroy($img);

使用函数说明

  1. imagecreatetruecolor — 新建一个真彩色图像
resource imagecreatetruecolor ( int $width , int $height )/*resource $image -->图像资源int $red , int $green , int $blue -->三原色值 0255 的整数或者十六进制的 0x000xFF*/

2.imagecolorallocate — 为一幅图像分配颜色

int imagecolorallocate ( resource $image , int $red , int $green , int $blue )/*resource $image -->图像资源int $red , int $green , int $blue -->三原色值 0255 的整数或者十六进制的 0x000xFF*/

3.imagefill — 区域填充

bool imagefill ( resource $image , int $x , int $y , int $color )/*resource $image -->图像资源int $x , int $y -->图像坐标,左上角为 (0, 0)int $color -->填充的颜色*/

4.imagestring — 水平地画一行字符串

bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )/*resource $image -->图像资源int $font -->字体 1,2,3,4,5为内置字体int $x , int $y -->起始位置string $s -->字符int $col -->颜色*/

5.imagesetpixel — 画一个单一像素

bool imagesetpixel ( resource $image , int $x , int $y , int $color )/*resource $image -->图像资源int $x , int $y -->位置int $color -->颜色*/

6.imagepng — 以 PNG 格式将图像输出到浏览器或文件

bool imagepng ( resource $image [, string $filename [, int value]] )/*resource $image -->图像资源string $filename -->如果用 filename 给出了文件名则将其输出到该文件int value -->质量参数 部分需要压缩的格式使用*/

7.imagedestroy — 销毁一图像

注意这里的销毁图像不是说删除图像文件,而是释放图片相关的内存资源。

bool imagedestroy ( resource $image )/*resource $image -->图像资源*/
0 0
原创粉丝点击