php图片验证码

  1. 启用phpGD库
  2. 部分GD库函数介绍
  3. 随机函数、16进制函数
  4. GD+SESSION制作验证码;
  5. image与header输出的介绍
  6. imageline (画线)与 imagesetpixel(设置像素,躁点) 函数
  7. imagettftext 函数调用字体写入文字
  8. PHP验证码插入中文的方法

 1 启用phpGD库

PHP 的GD库

GD库提供了一系列用来处理图片的API,使用GD库可以处理图片,或者生成图片;

在网站上GD库通常用来生成缩略图或者用来对图片加水印或者对网站数据生成报表;

打开gd库,默认关闭的;extension=php_gd2.dll前面的『;』去掉后就可以了,如果测试开启,

if(!function_exists("gd_info")){
    echo "no gd";
}else{ echo "yes";} 可以这样操作;

2部分GD库函数介绍

imagecreatetruecolor(int x_size,int y_size) // width & height; //画布大小

int imagecolorallocate ( resource $image , int $red , int $green , int $blue ) //颜色

note:第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色,即用 imagecreate()建立的图像。

imagestring(resource image,font(字体),int x,int y,内容,颜色); //绘图

在这里不得不再次说一遍,有些细节问题还是去看文档,文档里会写的更清楚,而且php文档大多数都汉化了;

3随机函数、16进制函数

rand([int min,int max]); min - max之间的随机数;

dechex(10进制数);这里用是为了获得颜色的值;

以2,3做出一个图片

//img.php
<?php
session_start();

// 验证码
$rn = "";
for($a=1;$a<=4;$a++){
    $rn .=dechex(rand(1,15));
}
$_SESSION["img"] = $rn;

$im = imagecreatetruecolor(100,40);

//allocate

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


imagestring($im,3,10,10,$rn,$te);

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

?>

请注意,这里是相当于用php生成了一张图片,而不是在页面里插入了一张图片,

4GD+SESSION制作验证码;

//sub.php

<?php
session_start();
if(@$_POST["sub"]){
    if($_POST["check"] == $_SESSION["img"]){
        echo "check success";
    }
}
?>

<form action="" method="post">

<IMG alt="" src="img.php"><br><br>
<INPUT type="text" name="check" placeholder="请输入验证码">
<INPUT type="submit" name="sub">

</form>

 显示,check success,简单的验证码验证到这儿就算好了;

HEADER

Content-Type: xxxxx(文件类型)/yyyyy(编码啊,格式啊)比如   image/jpeg  定义输出类型;让浏览器以什么类型来输出,比如图片,html文件,压缩文件格式等;

Location:???;

Status:???;

imageline,imagesetpixel

bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color );
bool imagesetpixel ( resource $image , int $x , int $y , int $color );
 
array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text );
 
<?php 
session_start();

$rn = "";
for($a=1;$a<=4;$a++){
    $rn .=dechex(rand(1,15));
}
$_SESSION["img"] = $rn;

$im = imagecreatetruecolor(100,40);


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

imagettftext($im,14,rand(-5,5),12,25,$te,"Pro.ttf","中文china");

for($i=1;$i<10;$i++){
    $te2 = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
    imagesetpixel($im,rand()*100,rand()*40,$te2);
    imageline ($im , rand(1,99) , rand(1,40) , rand(1,99) , rand(1,40) , $te2 );
}
header("Content-type:image/jpeg");
imagejpeg($im);

?>
原文地址:https://www.cnblogs.com/07byte/p/5950981.html