【PHP】解析PHP的GD库

官方文档:http://php.net/manual/en/book.image.php

1.GD库简介

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的详细信息

<?php
$gdinfoarr = gd_info();
foreach($gdinfoarr as $e => $v){
   echo $e." = ".$v."<br/>";
}
?>

输出结果:

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库的版本信息。

2.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);  
?>

输出结果如下:

3.绘制验证码功能

上面我们已经了知道了GD库的基本使用,下面显示图片验证码功能

login.html 文件

<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 文件

<?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
效果图:

这里的验证码很“规矩”,可以对上面的验证码拓展,比如渐变背景,干扰线,多种文字,文字旋转,不同字体 等等。

原文地址:https://www.cnblogs.com/HDK2016/p/10213831.html