加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

GD库的基本信息,图像的旋转、水印、缩略图、验证码,以及图像类

发布时间:2020-12-13 20:55:27 所属栏目:PHP教程 来源:网络整理
导读:GD库检测 ? php phpinfo (); ? ? ? ? GD库安装 ? Windows 使用phpstudy ? Linux 编译安装 –with-gd ? Linux 编译安装扩展 GD库支持的图像格式 使用 gd_info() 函数 检测服务器支持的图像格式 ? 图像信息处理 ? ? ? // 获取图像详细信息 $image = '../image/

GD库检测

<?php
phpinfo();
?>

?

?

?

GD库安装
? Windows 使用phpstudy

? Linux 编译安装 –with-gd
? Linux 编译安装扩展


GD库支持的图像格式

使用 gd_info() 函数 检测服务器支持的图像格式

?

图像信息处理

?

?

<?//获取图像详细信息
$image = '../image/b.png';
$info = getimagesize($image);
var_dump($info);

$string = file_get_contents();
$info = getimagesizefromstring($string);

获取图像的文件后缀
$imageType = image_type_to_extension($info[2],false$imageType);string(3) "png"
//获取图像的mime type
$mime = image_type_to_mime_type($info[2]);
$mime);string(9) "image/png"
//创建图像
$im = imagecreatefrompng(echo sprintf('a.jpg 宽:%s,高:%s',imagesx($im),imagesy($im));a.jpg 宽:543,高:299

//根据不同的图像type 来创建图像
switch(])
{
    case 1:IMAGETYPE_GIF
        $im = imagecreatefromgif();
        break;
    case IMAGETYPE_JPEG:
        $im = imagecreatefromjpeg(case 3:
        ;

    default:
        echo '图像格式不支持';
        ;

}

随机显示图片

/**
 * 创建图像
 * 设置背景色
 * 输出图像
 *
 */

创建图像 imagecreate();
$im = imagecreatetruecolor(200,200$back = imagecolorallocate($im,1)">mt_rand(200,255),255));
imagefill($back设置header mime type
header('Content-type:image/png');
imagepng(随机输出图像到浏览器中
$imageList = array(
    '../image/a.jpg','../image/b.png',1)">
);

$imageKey = array_rand($imageList$image = $imageList[$imageKey];
获取图像信息
根据图像类别不同 调用不同的创建图像函数
;

}
设置header mime type
$mimeType = header('Content-Type:'.$mimeType根据image type调用不同的图像输出类型
IMAGETYPE_GIF
        imagegif($imcase IMAGETYPE_JPEG:
        imagejpeg(null,60case 3:
        imagepng(;
}

imagedestroy($im);

图像旋转

旋转图像
$im = imagecreatefrompng('../image/b.png'$rotate = imagerotate(header('Content-type:image/jpeg');
imagejpeg($rotate);

缩略图(图片放大缩小)

<?*
 * 缩略图
 *
 创建原图
$srcIm = imagecreatefromjpeg('../image/a.jpg'$srcW = imagesx($srcIm$srcH = imagesy($percent = 0.5;

$desW = $srcW * $percent$desH = $srcH * ;

创建新图
$desIm = imagecreatetruecolor($desW,1)">$desH拷贝图像并调整大小
//imagecopyresized();

//重采样拷贝图像并调整大小
imagecopyresampled($desIm,1)">$srcIm,1)">$desH,1)">$srcW,1)">$srcH生成图
imagejpeg($desW}_{$desH}.jpg",75imagepng($desIm,"../image/a_{$desW}_{$desH}.png");

//生成的图像会自动出现在image文件夹中,不会出现在页面上

图像拷贝(生成水印)

$logo = imagecreatefrompng('../image/logo.png'把logo图片从x y开始宽度为w 高度为h的部分图像拷贝到im图像的x y坐标上
imagecopy($logo,400,200,1)">$logo),1)">$logo));

透明度拷贝
imagecopymerge(header('Content-Type:image/png');

imagepng($im);

图像中显示文字

创建画布
$im = imagecreatetruecolor(400,250),250创建字体颜色
$stringColor = imagecolorallocate(mt_rand(50,150),150));
图像中水平写入字符串
//imagestring只能使用系统字体
imagestring(mt_rand(20,1)">$im)-50),1)">mt_rand(10,1)">$im)),'hello',1)">$stringColor垂直写入字符串
//imagestringup($im,mt_rand(20,imagesx($im)-50),mt_rand(10,imagesy($im)),$stringColor);

$im);

随机四位数验证码

生成随机字符串
$string = 'abcdefg123456789ABCDEFGHIGK'$str='';
for($i=0;$i<4;$i++)
{
    $str.= $string[mt_rand(0,1)">strlen($string)-1)];
}

图像中写入字符串
imagestring($str,1)">$im);
imagettftext()可以使用自定义字体,然鹅
使用“imagettftext()”函数时,字体路径要写带盘符的绝对路径,写相对路径就报错
比如改成:
D:phpstudy_proWWWphptestgdfontcomicz.ttf
imagettftext(mt_rand(-10,10),1)">$stringColor,'./font/comicz.ttf',1)">$str);

四色随机验证码

<?php

));
    $str = )];
    图像中写入字符串
    imagettftext($i*15,100,'D:phpstudy_proWWWphptestgdfontcomicz.ttf',1)">$str);
}

$im);

?

?

?各种图形绘制

<?*
 * 图形绘制
 * 绘画复杂图形
 画布
画点
$black = imagecolorallocate($i<150;)
{
    imagesetpixel($black画线
$red = imagecolorallocate($j = 0; $j < 3; $j++)
{
    imageline($red);

}

设置线条粗细
imagesetthickness();
imageline($style = array($red,1)">$back,1)">设置划线的风格
imagesetstyle($style设置划线的风格
imageline(IMG_COLOR_STYLED);

画矩形
imagerectangle(画圆
imageellipse(header('Content-Type:image/jpeg'

?

?

?验证码类的封装

GD库检测文件 GDBasic.php

<?*
 * GDBasic.php
 * description GD基础类
 */

namespace TestLib;


class GDBasic
{
    protected static $_check =检查服务器环境中gd库
    public static function check()
    {
        当静态变量不为false
        if(static::$_check)
        {
            return true;
        }

        检查gd库是否加载
        if(!function_exists("gd_info"))
        {
            throw new Exception('GD is not exists');
        }

        检查gd库版本
        $version = '';
        $info = gd_info();
        preg_match("/d+.d+(?:.d+)?/",1)">$info["GD Version"],1)">$matches))
        {
            $version = $matches[0];
        }

        当gd库版本小于2.0.1
        version_compare($version,'2.0.1','>='Exception("GD requires GD version '2.0.1' or greater,you have " . $version);
        }

        self::$_check = return self::;
    }
}

验证码类的文件Captcha.php

<?*
 * Captcha.php
 * description 验证码类
 

namespace TestLib;

require_once 'GDBasic.php'class Captcha extends图像宽度
    protected $_width = 60图像高度
    $_height = 25随机串
    $_code = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjklmnpqrstuvwxyz'字体文件
    $_font_file = 'D:phpstudy_proWWWphptestgdfontcomicz.ttf'图像
    $_im验证码
    $_captchafunction __construct($width = $height = null)
    {
        self::check();
        $this->create($width,1)">$height);
    }

    *
     * 创建图像
     * @param $width
     * @param $height
     */
    function create()
    {
        $this->_width = is_numeric($width) ? $width : $this->_width;
        $this->_height = $height) ? $height : _height;
        创建图像
        $im = imagecreatetruecolor($this->_width,1)">_height);
        ));
        填充底色
        imagefill();
        $this->_im = ;
    }

    *
     * 混乱验证码
      moll()
    {
        $this->_im,1)">在图像中随机生成50个点
        $i = 0; $i < 50; )
        {
            imagesetpixel($this->_width),1)">$this->_height),1)">);
        }

        imageline();

        imageline();
    }


    *
     * 生成验证码随机串
     * @param int $length 验证码的个数
     * @param int $fontSize 字符串的字体大小
     * @return Captcha
     function string($length = 4,1)">$fontSize = 15moll();
        $code = _code;
        $captcha = ''$i < $length; )
        {
            $string = $code[$code) - 1)];
            $strColor = imagecolorallocate(mt_rand(100,1)">));
            imagettftext($fontSize,1)">mt_rand(3,6) + $i * (($this->_width - 10) / $length),($this->_height / 3) * 2,1)">$strColor,1)">$this->_font_file,1)">);
            $captcha .= ;
        }

        $this->_captcha = $captchareturn $this;
    }


    *
     * 验证码存入session
      setSession()
    {
        isset($_SESSIONsession_start();
        }
        $_SESSION['captcha_code'] = _captcha;
    }

    *
     * 逻辑运算符验证码
     * @param int $fontSize 字体大小
     * @return $this
     function logic($fontSize = 12$codeArray = array(1 => 1,2,3,4,6,7,8,9$operatorArray = array('+' => '+','-' => '-','x' => '*'list($first,1)">$second) = $codeArray,2$operator = $operatorArray$captcha = 0$string = ''$operatorcase '+':
                $captcha = $first + $second;
                ;
            case '-':
                当第一个数小于第二个数
                if($first < )
                {
                    $second,1)">$first);
                }
                $first - ;

            case 'x':
                $first * ;
        }
        设置验证码类变量
        要输出到图像中的字符串
        sprintf('%s%s%s=?',1)">$operator,1)">);

        ));
        imagettftext();

        *
     * 输出验证码
      show()
    {
        生成session
        setSession();
        );
        imagejpeg(_im);
        imagedestroy(_im);
    }
}

检测GD库演示

检测GD库
 gd_info();
$matches);0 => string '2.1.0' (length=5)

6位随机数验证码演示

require_once './lib/Captcha.php'$captcha = new TestLibCaptcha(80,30$captcha->string(6,14)->show();6位数随机验证码

?

?

逻辑计算验证码演示

$captcha->logic(12)->show();

?

?

图片类封装?Image.php

<?*
 * Image.php
 * author: F.X
 * date: 2017
 * description 图像类
 class Image $_width$_height$_type$_mime$_real_path;

    
    $file)
    {
        检查GD库
        self::$imageInfo = $this->createImageByFile($this->_width = $imageInfo['width'];
        $this->_height = $imageInfo['height'$imageInfo['im'$this->_type = $imageInfo['type'$this->_real_path = $imageInfo['real_path'$this->_mime = $imageInfo['mime'];
    }


    *
     * 根据文件创建图像
     * @param $file
     * @return array
     * @throws Exception
     function createImageByFile(检查文件是否存在
        file_exists(Exception('file is not exits'获取图像信息
        $imageInfo = $realPath = realpath(if(!$imageInfoException('file is not image file'$imageInfo[2])
        {
            case IMAGETYPE_GIF:
                );
                case IMAGETYPE_JPEG:
                case IMAGETYPE_PNG:
                default:
                throw  Exception('image file must be png,jpeg,gif'(
            'width'     => $imageInfo[0],'height'    => $imageInfo[1],'type'      => $imageInfo[2],'mime'      => $imageInfo['mime'],'im'        => $realPath,1)">
        );

    }

    *
     * 缩略图
     * @param  int $width 缩略图高度
     * @param  int $height 缩略图宽度
     * @return $this
     * @throws Exception
     function resize($width) || !Exception('image width or height must be number');
        }
        根据传参的宽高获取最终图像的宽高
        $srcW = $srcH = _height;

        $width <= 0 || $height <= 0$srcW;缩略图高度
            $srcH;缩略图宽度
        }
        else
        {
            $srcP = $srcW / 宽高比
            $desP = $width / $width > $srcW)
            {
                $height > )
                {
                    ;
                    ;
                }
                
                {
                    $desW = round($desH * $srcP);
                }
            }
            
            {
                $desP > $width$desH = $desW / );
                }
                );
                }
            }
        }

        PHP版本小于5.5
        version_compare(PHP_VERSION,'5.5.0','<');
            if(imagecopyresampled())
            {
                imagedestroy(_im);
                $desIm;
                $this->_width = imagesx($this->_height = imagesy(_im);
            }
        }
        
        {
            $desIm = imagescale())
            {
                _im);
            }

        }

        *
     * 根据百分比生成缩略图
     * @param int $percent 1-100
     * @return Image
     * @throws Exception
     function resizeByPercent(intval($percent) <= 0Exception('percent must be gt 0');
        }

        $percent = $percent) > 100 ? 100 : $percent = $percent / 100;

        $this->_width * $this->_height * $this->resize(*
     * 图像旋转
     * @param $degree
     * @return $this
     function rotate($degree$degree = 360 - $back = imagecolorallocatealpha($im = imagerotate($degree,1);
        imagesavealpha();
        imagedestroy(_im);
        _im);
        *
     * 生成水印
     * @param file $water 水印图片
     * @param int $pct   透明度
     * @return $this
     function waterMask($water ='',1)">$pct = 60 )
    {
        根据水印图像文件生成图像资源
        $waterInfo = $water);
        imagecopymerge();
        销毁$this->_im
        $waterInfo['im';

    }

    
    *
     * 图片输出
     * @return bool
     header('Content-Type:' . _mime);
        $this->_type == 1)
        {
            imagegif(_im);
            $this->_type == 2)
        {
            imagejpeg($this->_type == 3)
        {
            imagepng(;
        }
    }

    *
     * 保存图像文件
     * @param $file
     * @param null $quality
     * @return bool
     * @throws Exception
     function save($file,1)">$quality = 获取保存目的文件的扩展名
        $ext = pathinfo( PATHINFO_EXTENSION);
        strtolower($ext$ext || !in_array($ext,1)">array('jpg','jpeg','gif','png')))
        {
            Exception('image save file must be jpg,png,1)">$ext === 'gif'$ext === 'jpeg' || $ext === 'jpg'$quality > 0$quality < 1$quality = 1$quality > 100$quality = 100;
                }

                imagejpeg($quality);
            }
            
            {
                imagejpeg($ext === 'png';
        }

    }
}

指定尺寸缩放 演示

require_once './lib/Image.php'$image = new TestLibImage('../image/b.png'$image->resize(400,200)->save('../image/b_400_200.png');

?

?

按比例缩放+旋转 演示

$image->resizeByPercent(50)->rotate(1800)->show();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读