官方文档:http://php.net/manual/en/book.image.phpphp
PHP能够建立和操做多种不一样格式的图像文件。PHP提供了一些内置的图像信息函数,也可使用GD函数库建立和处理已有的函数库。目前GD2库支持GIF、JPEG、PNG和WBMP等格式。此外还支持一些FreeType、Type1等字体库。
首先要在PHP的配置文件(php.ini)中打开php_gd2的扩展
若是有其余的集成软件,能够直接勾选上php_gd2。笔者使用的wampserver,就能够直接勾选上php的php_gd2扩展:
一般状况下,php_gd2扩展默认是开启的。
经过gd_info()得到有关GD的详细信息html
<?php $gdinfoarr = gd_info(); foreach($gdinfoarr as $e => $v){ echo $e." = ".$v."<br/>"; } ?>
输出结果:app
GD Version = bundled (2.1.0 compatible)
FreeType Support = 1
FreeType Linkage = with freetype
T1Lib Support =
GIF Read Support = 1
GIF Create Support = 1
JPEG Support = 1
PNG Support = 1
WBMP Support = 1
XPM Support = 1
XBM Support = 1
JIS-mapped Japanese Font Support =
其中1表明支持的功能,空表明不支持。从上面也能够看到GD库的版本信息。函数
在PHP中建立一个图像一般应该完成4步:
1.建立一个背景图像(也叫画布),之后的操做都是基于该图像
2.在背景上绘制图像信息
3.输出图像
4.释放资源
字体
<?php //1. 建立画布 $im = imageCreateTrueColor(200, 200); //创建空白背景 $white = imageColorAllocate ($im, 255, 255, 255); //设置绘图颜色 $blue = imageColorAllocate ($im, 0, 0, 64); //2. 开始绘画 imageFill($im, 0, 0, $blue); //绘制背景 imageLine($im, 0, 0, 200, 200, $white); //画线 imageString($im, 4, 50, 150, 'Sales', $white); //添加字串 //3. 输出图像 header('Content-type: image/png'); imagePng ($im); //以 PNG 格式将图像输出 //4. 释放资源 imageDestroy($im); ?>
输出结果以下:spa
上面咱们已经了知道了GD库的基本使用,下面显示图片验证码功能
login.html 文件.net
<html> <head> <title> login </title> </head> <body> <div> <div><span>username:</span><span><input type="text"/></span></div> <div><span>password:</span><span><input type="password"></span></div> <div> <span>verify:</span> <span><input type="text"/></span> <span><img alt="img" src="verifycode.php"></span> </div> <div> <input type="submit" value="submit"> </div> </div> </body> </html>
verifycode.php 文件code
<?php //建立画布 $im = imageCreateTrueColor(80, 40); //建立画笔 $red = imageColorAllocate ($im, 255,0,0); $black = imageColorAllocate ($im, 0, 0, 0); //将整个画布铺为红色 imagefill($im, 0, 0, $red); $verify = ""; do{ $v = rand(0, 9); $verify = $verify.$v;//.表示字符串拼接符,将原有的验证数字和新的验证数字拼接起来 }while( strlen($verify) < 4 ); $_SESSION["verifycode"] = $verify;//将值存储到SESSION变量中 $font = 'arial.ttf'; imagettftext($im, 20, 0, 10,30, $black,$font,$verify);//将验证码绘制到画布上 header('Content-type: image/png'); imagePng ($im); //以 PNG 格式将图像输出 //释放资源 imageDestroy($im);
而后访问 http://localhost/Test/login.html
效果图:server
这里的验证码很“规矩”,能够对上面的验证码拓展,好比渐变背景,干扰线,多种文字,文字旋转,不一样字体 等等。htm