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

15 篇文章 0 订阅

使用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 -->图像资源
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值