使用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);
使用函数说明
- imagecreatetruecolor — 新建一个真彩色图像
resource imagecreatetruecolor ( int $width , int $height )
/*
resource $image -->图像资源
int $red , int $green , int $blue -->三原色值 0 到 255 的整数或者十六进制的 0x00 到 0xFF
*/
2.imagecolorallocate — 为一幅图像分配颜色
int imagecolorallocate ( resource $image , int $red , int $green , int $blue )
/*
resource $image -->图像资源
int $red , int $green , int $blue -->三原色值 0 到 255 的整数或者十六进制的 0x00 到 0xFF
*/
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 -->图像资源
*/