GD庫的基本信息,圖像的旋轉、水印、縮略圖、驗證碼,以及圖像類的封裝

GD庫檢測php

<?php
phpinfo();
?>

 

 

 

GD庫安裝
• Windows 使用phpstudy瀏覽器

• Linux 編譯安裝 –with-gd
• Linux 編譯安裝擴展服務器


GD庫支持的圖像格式session

使用 gd_info() 函數 檢測服務器支持的圖像格式函數

 

圖像信息處理字體

 

 

<?php
//獲取圖像詳細信息
$image = '../image/b.png';
$info = getimagesize($image);
var_dump($info);

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

//獲取圖像的文件後綴
$imageType = image_type_to_extension($info[2],false);
var_dump($imageType);//string(3) "png"
//獲取圖像的mime type
$mime = image_type_to_mime_type($info[2]);
var_dump($mime);//string(9) "image/png"
//建立圖像
$im = imagecreatefrompng($image);
echo sprintf('a.jpg 寬:%s,高:%s',imagesx($im),imagesy($im));//a.jpg 寬:543,高:299

//根據不一樣的圖像type 來建立圖像
switch($info[2])
{
    case 1://IMAGETYPE_GIF
        $im = imagecreatefromgif($image);
        break;
    case IMAGETYPE_JPEG:
        $im = imagecreatefromjpeg($image);
        break;
    case 3:
        $im = imagecreatefrompng($image);
        break;

    default:
        echo '圖像格式不支持';
        break;

}

隨機顯示圖片ui

/**
 * 建立圖像
 * 設置背景色
 * 輸出圖像
 *
 */

//建立圖像 imagecreate();
$im = imagecreatetruecolor(200,200);
$back = imagecolorallocate($im,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
imagefill($im,0,0,$back);

//設置header mime type
header('Content-type:image/png');
imagepng($im,'../image/back.png');

//隨機輸出圖像到瀏覽器中
$imageList = array(
    '../image/a.jpg',
    '../image/b.png',
    '../image/back.png'
);

$imageKey = array_rand($imageList);
$image = $imageList[$imageKey];
//獲取圖像信息
$info = getimagesize($image);

//根據圖像類別不一樣 調用不一樣的建立圖像函數
switch($info[2])
{
    case 1://IMAGETYPE_GIF
        $im = imagecreatefromgif($image);
        break;
    case IMAGETYPE_JPEG:
        $im = imagecreatefromjpeg($image);
        break;
    case 3:
        $im = imagecreatefrompng($image);
        break;

    default:
        echo '圖像格式不支持';
        break;

}
//設置header mime type
$mimeType = image_type_to_mime_type($info[2]);
header('Content-Type:'.$mimeType);

//根據image type調用不一樣的圖像輸出類型
switch($info[2])
{
    case 1://IMAGETYPE_GIF
        imagegif($im);
        break;
    case IMAGETYPE_JPEG:
        imagejpeg($im,null,60);
        break;
    case 3:
        imagepng($im);
        break;
}

imagedestroy($im);

圖像旋轉this

//旋轉圖像
$im = imagecreatefrompng('../image/b.png');

$back = imagecolorallocate($im,233,230,232);
$rotate = imagerotate($im,75,$back);

header('Content-type:image/jpeg');
imagejpeg($rotate);

縮略圖(圖片放大縮小)spa

<?php
/**
 * 縮略圖
 *
 */

//建立原圖
$srcIm = imagecreatefromjpeg('../image/a.jpg');

$srcW = imagesx($srcIm);
$srcH = imagesy($srcIm);

$percent = 0.5;

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

//建立新圖
$desIm = imagecreatetruecolor($desW, $desH);

//拷貝圖像並調整大小
//imagecopyresized();

//重採樣拷貝圖像並調整大小
imagecopyresampled($desIm, $srcIm, 0, 0, 0, 0, $desW, $desH, $srcW, $srcH);

//生成圖
imagejpeg($desIm, "../image/a_{$desW}_{$desH}.jpg", 75);
//imagepng($desIm,"../image/a_{$desW}_{$desH}.png");

//生成的圖像會自動出如今image文件夾中,不會出如今頁面上

圖像拷貝(生成水印)3d

$im = imagecreatefrompng('../image/b.png');

$logo = imagecreatefrompng('../image/logo.png');

//把logo圖片從x y開始寬度爲w 高度爲h的部分圖像拷貝到im圖像的x y座標上
imagecopy($im,$logo,400,200,0,0,imagesx($logo),imagesy($logo));

//透明度拷貝
imagecopymerge($im,$logo,400,200,0,0,imagesx($logo),imagesy($logo),10);
header('Content-Type:image/png');

imagepng($im);

圖像中顯示文字

//建立畫布
$im = imagecreatetruecolor(400,200);
$back = imagecolorallocate($im,mt_rand(200,250),mt_rand(200,250),mt_rand(200,250));
imagefill($im,0,0,$back);

//建立字體顏色
$stringColor = imagecolorallocate($im,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150));
//圖像中水平寫入字符串
//imagestring只能使用系統字體
imagestring($im,5,mt_rand(20,imagesx($im)-50),mt_rand(10,imagesy($im)),'hello',$stringColor);
//垂直寫入字符串
//imagestringup($im,5,mt_rand(20,imagesx($im)-50),mt_rand(10,imagesy($im)),'hello',$stringColor);

header('Content-Type:image/png');
imagepng($im);

隨機四位數驗證碼

//建立畫布
$im = imagecreatetruecolor(400,200);
$back = imagecolorallocate($im,mt_rand(200,250),mt_rand(200,250),mt_rand(200,250));
imagefill($im,0,0,$back);

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

//圖像中寫入字符串
imagestring($im,5,mt_rand(20,imagesx($im)-50),mt_rand(10,imagesy($im)),$str,$stringColor);

header('Content-Type:image/png');
imagepng($im);
imagettftext()可使用自定義字體,然鵝
使用「imagettftext()」函數時,字體路徑要寫帶盤符的絕對路徑,寫相對路徑就報錯
好比改爲:
D:\phpstudy_pro\WWW\phptest\gd\font\comicz.ttf
imagettftext($im,15,mt_rand(-10,10),mt_rand(20,imagesx($im)-50),mt_rand(10,imagesy($im)),$stringColor,'./font/comicz.ttf',$str);

四色隨機驗證碼

<?php

//建立畫布
$im = imagecreatetruecolor(400,200);
$back = imagecolorallocate($im,mt_rand(200,250),mt_rand(200,250),mt_rand(200,250));
imagefill($im,0,0,$back);

//生成隨機字符串
$string = 'abcdefg123456789ABCDEFGHIGK';

for($i=0;$i<4;$i++)
{
    $stringColor = imagecolorallocate($im,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150));
    $str = $string[mt_rand(0,strlen($string)-1)];
    //圖像中寫入字符串
    imagettftext($im,15,mt_rand(-10,10),20+$i*15,100,$stringColor,'D:\phpstudy_pro\WWW\phptest\gd\font\comicz.ttf',$str);
}

header('Content-Type:image/png');
imagepng($im);

 

 

 各類圖形繪製

<?php
/**
 * 圖形繪製
 * 繪畫複雜圖形
 */

//畫布
$im = imagecreatetruecolor(400, 200);
$back = imagecolorallocate($im, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imagefill($im, 0, 0, $back);

//畫點
$black = imagecolorallocate($im,10,10,10);
for($i=0;$i<150;$i++)
{
    imagesetpixel($im,mt_rand(10,390),mt_rand(10,190),$black);
}

//畫線
$red = imagecolorallocate($im, 10, 0, 0);
for($j = 0; $j < 3; $j++)
{
    imageline($im, mt_rand(10, 400), mt_rand(10, 200), mt_rand(10, 400), mt_rand(10, 200), $red);

}

//設置線條粗細
imagesetthickness($im,5);
imageline($im, mt_rand(10, 400), mt_rand(10, 200), mt_rand(10, 400), mt_rand(10, 200), $red);

$style = array($red,$red,$red,$red,$red,$back,$back,$back,$back,$back);

//設置劃線的風格
imagesetstyle($im,$style);

//設置劃線的風格
imageline($im,10,50,250,200,IMG_COLOR_STYLED);

//畫矩形
imagerectangle($im,50,50,150,150,$red);

//畫圓
imageellipse($im,200,100,100,100,$red);

header('Content-Type:image/jpeg');
imagejpeg($im, null, 70);

 

 

 驗證碼類的封裝

GD庫檢測文件 GDBasic.php

<?php
/**
 * GDBasic.php
 * description GD基礎類
 */

namespace Test\Lib;


class GDBasic
{
    protected static $_check =false;

    //檢查服務器環境中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();
        if(preg_match("/\\d+\\.\\d+(?:\\.\\d+)?/", $info["GD Version"], $matches))
        {
            $version = $matches[0];
        }

        //當gd庫版本小於2.0.1
        if(!version_compare($version,'2.0.1','>='))
        {
            throw new \Exception("GD requires GD version '2.0.1' or greater, you have " . $version);
        }

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

驗證碼類的文件Captcha.php

<?php
/**
 * Captcha.php
 * description 驗證碼類
 */

namespace Test\Lib;

require_once 'GDBasic.php';

class Captcha extends GDBasic
{
    //圖像寬度
    protected $_width = 60;
    //圖像高度
    protected $_height = 25;

    //隨機串
    protected $_code = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjklmnpqrstuvwxyz';

    //字體文件
    protected $_font_file = 'D:\phpstudy_pro\WWW\phptest\gd\font\comicz.ttf';

    //圖像
    protected $_im;
    //驗證碼
    protected $_captcha;

    public function __construct($width = null, $height = null)
    {
        self::check();
        $this->create($width, $height);
    }

    /**
     * 建立圖像
     * @param $width
     * @param $height
     */
    public function create($width, $height)
    {
        $this->_width = is_numeric($width) ? $width : $this->_width;
        $this->_height = is_numeric($height) ? $height : $this->_height;
        //建立圖像
        $im = imagecreatetruecolor($this->_width, $this->_height);
        $back = imagecolorallocate($im, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
        //填充底色
        imagefill($im, 0, 0, $back);
        $this->_im = $im;
    }

    /**
     * 混亂驗證碼
     */
    public function moll()
    {
        $back = imagecolorallocate($this->_im, 0, 0, 0);
        //在圖像中隨機生成50個點
        for($i = 0; $i < 50; $i++)
        {
            imagesetpixel($this->_im, mt_rand(0, $this->_width), mt_rand(0, $this->_height), $back);
        }

        imageline($this->_im, mt_rand(0, $this->_width), mt_rand(0, $this->_height), mt_rand(0, $this->_width), mt_rand(0, $this->_height), $back);

        imageline($this->_im, mt_rand(0, $this->_width), mt_rand(0, $this->_height), mt_rand(0, $this->_width), mt_rand(0, $this->_height), $back);
    }


    /**
     * 生成驗證碼隨機串
     * @param int $length 驗證碼的個數
     * @param int $fontSize 字符串的字體大小
     * @return Captcha
     */
    public function string($length = 4, $fontSize = 15)
    {
        $this->moll();
        $code = $this->_code;
        $captcha = '';
        for($i = 0; $i < $length; $i++)
        {
            $string = $code[mt_rand(0, strlen($code) - 1)];
            $strColor = imagecolorallocate($this->_im, mt_rand(100, 150), mt_rand(100, 150), mt_rand(100, 150));
            imagettftext($this->_im, $fontSize, mt_rand(-10, 10), mt_rand(3, 6) + $i * (($this->_width - 10) / $length), ($this->_height / 3) * 2, $strColor, $this->_font_file, $string);
            $captcha .= $string;
        }

        $this->_captcha = $captcha;
        return $this;
    }


    /**
     * 驗證碼存入session
     */
    public function setSession()
    {
        if(!isset($_SESSION))
        {
            session_start();
        }
        $_SESSION['captcha_code'] = $this->_captcha;
    }

    /**
     * 邏輯運算符驗證碼
     * @param int $fontSize 字體大小
     * @return $this
     */
    public function logic($fontSize = 12)
    {
        $this->moll();
        $codeArray = array(1 => 1, 2, 3, 4, 5, 6, 7, 8, 9);
        $operatorArray = array('+' => '+', '-' => '-', 'x' => '*');
        list($first, $second) = array_rand($codeArray, 2);
        $operator = array_rand($operatorArray);
        $captcha = 0;
        $string = '';
        switch($operator)
        {
            case '+':
                $captcha = $first + $second;
                break;
            case '-':
                //當第一個數小於第二個數
                if($first < $second)
                {
                    list($first, $second) = array($second, $first);
                }
                $captcha = $first - $second;
                break;

            case 'x':
                $captcha = $first * $second;
                break;
        }
        //設置驗證碼類變量
        $this->_captcha = $captcha;
        //要輸出到圖像中的字符串
        $string = sprintf('%s%s%s=?', $first, $operator, $second);

        $strColor = imagecolorallocate($this->_im, mt_rand(100, 150), mt_rand(100, 150), mt_rand(100, 150));
        imagettftext($this->_im, $fontSize, 0, 5, ($this->_height / 3) * 2, $strColor, $this->_font_file, $string);

        return $this;
    }


    /**
     * 輸出驗證碼
     */
    public function show()
    {
        //生成session
        $this->setSession();
        header('Content-Type:image/jpeg');
        imagejpeg($this->_im);
        imagedestroy($this->_im);
    }
}

檢測GD庫演示

//檢測GD庫
$info = gd_info();
preg_match("/\\d+\\.\\d+(?:\\.\\d+)?/", $info["GD Version"], $matches);
var_dump($matches);//0 => string '2.1.0' (length=5)

6位隨機數驗證碼演示

require_once './lib/Captcha.php';

$captcha = new \Test\Lib\Captcha(80,30);

$captcha->string(6,14)->show();//6位數隨機驗證碼

 

 

邏輯計算驗證碼演示

require_once './lib/Captcha.php';

$captcha = new \Test\Lib\Captcha(80,30);

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

 

 

圖片類封裝 Image.php

<?php
/**
 * Image.php
 * author: F.X
 * date: 2017
 * description 圖像類
 */

namespace Test\Lib;

require_once 'GDBasic.php';

class Image extends GDBasic
{
    protected $_width;
    protected $_height;
    protected $_im;
    protected $_type;
    protected $_mime;
    protected $_real_path;

    
    public function __construct($file)
    {
        //檢查GD庫
        self::check();
        $imageInfo = $this->createImageByFile($file);
        $this->_width = $imageInfo['width'];
        $this->_height = $imageInfo['height'];
        $this->_im = $imageInfo['im'];
        $this->_type = $imageInfo['type'];
        $this->_real_path = $imageInfo['real_path'];
        $this->_mime = $imageInfo['mime'];
    }


    /**
     * 根據文件建立圖像
     * @param $file
     * @return array
     * @throws \Exception
     */
    public function createImageByFile($file)
    {
        //檢查文件是否存在
        if(!file_exists($file))
        {
            throw new \Exception('file is not exits');
        }

        //獲取圖像信息
        $imageInfo = getimagesize($file);
        $realPath = realpath($file);
        if(!$imageInfo)
        {
            throw new \Exception('file is not image file');
        }

        switch($imageInfo[2])
        {
            case IMAGETYPE_GIF:
                $im = imagecreatefromgif($file);
                break;
            case IMAGETYPE_JPEG:
                $im = imagecreatefromjpeg($file);
                break;
            case IMAGETYPE_PNG:
                $im = imagecreatefrompng($file);
                break;
            default:
                throw  new \Exception('image file must be png,jpeg,gif');
        }

        return array(
            'width'     => $imageInfo[0],
            'height'    => $imageInfo[1],
            'type'      => $imageInfo[2],
            'mime'      => $imageInfo['mime'],
            'im'        => $im,
            'real_path' => $realPath,
        );

    }

    /**
     * 縮略圖
     * @param  int $width 縮略圖高度
     * @param  int $height 縮略圖寬度
     * @return $this
     * @throws \Exception
     */
    public function resize($width, $height)
    {
        if(!is_numeric($width) || !is_numeric($height))
        {
            throw new \Exception('image width or height must be number');
        }
        //根據傳參的寬高獲取最終圖像的寬高
        $srcW = $this->_width;
        $srcH = $this->_height;

        if($width <= 0 || $height <= 0)
        {
            $desW = $srcW;//縮略圖高度
            $desH = $srcH;//縮略圖寬度
        }
        else
        {
            $srcP = $srcW / $srcH;//寬高比
            $desP = $width / $height;

            if($width > $srcW)
            {
                if($height > $srcH)
                {
                    $desW = $srcW;
                    $desH = $srcH;
                }
                else
                {
                    $desH = $height;
                    $desW = round($desH * $srcP);
                }
            }
            else
            {
                if($desP > $srcP)
                {
                    $desW = $width;
                    $desH = round($desW / $srcP);
                }
                else
                {
                    $desH = $height;
                    $desW = round($desH * $srcP);
                }
            }
        }

        //PHP版本小於5.5
        if(version_compare(PHP_VERSION, '5.5.0', '<'))
        {
            $desIm = imagecreatetruecolor($desW, $desH);
            if(imagecopyresampled($desIm, $this->_im, 0, 0, 0, 0, $desW, $desH, $srcW, $srcH))
            {
                imagedestroy($this->_im);
                $this->_im = $desIm;
                $this->_width = imagesx($this->_im);
                $this->_height = imagesy($this->_im);
            }
        }
        else
        {
            if($desIm = imagescale($this->_im, $desW, $desH))
            {
                $this->_im = $desIm;
                $this->_width = imagesx($this->_im);
                $this->_height = imagesy($this->_im);
            }

        }

        return $this;
    }


    /**
     * 根據百分比生成縮略圖
     * @param int $percent 1-100
     * @return Image
     * @throws \Exception
     */
    public function resizeByPercent($percent)
    {
        if(intval($percent) <= 0)
        {
            throw new \Exception('percent must be gt 0');
        }

        $percent = intval($percent) > 100 ? 100 : intval($percent);

        $percent = $percent / 100;

        $desW = $this->_width * $percent;
        $desH = $this->_height * $percent;
        return $this->resize($desW, $desH);
    }


    /**
     * 圖像旋轉
     * @param $degree
     * @return $this
     */
    public function rotate($degree)
    {
        $degree = 360 - intval($degree);
        $back = imagecolorallocatealpha($this->_im,0,0,0,127);
        $im = imagerotate($this->_im,$degree,$back,1);
        imagesavealpha($im,true);
        imagedestroy($this->_im);
        $this->_im = $im;
        $this->_width = imagesx($this->_im);
        $this->_height = imagesy($this->_im);
        return $this;
    }


    /**
     * 生成水印
     * @param file $water 水印圖片
     * @param int $pct   透明度
     * @return $this
     */
    public function waterMask($water ='',$pct = 60 )
    {
        //根據水印圖像文件生成圖像資源
        $waterInfo = $this->createImageByFile($water);
        imagecopymerge();
        //銷燬$this->_im
        $this->_im = $waterInfo['im'];
        $this->_width = imagesx($this->_im);
        $this->_height = imagesy($this->_im);
        return $this;

    }

    
    /**
     * 圖片輸出
     * @return bool
     */
    public function show()
    {
        header('Content-Type:' . $this->_mime);
        if($this->_type == 1)
        {
            imagegif($this->_im);
            return true;
        }

        if($this->_type == 2)
        {
            imagejpeg($this->_im, null, 80);
            return true;
        }

        if($this->_type == 3)
        {
            imagepng($this->_im);
            return true;
        }
    }

    /**
     * 保存圖像文件
     * @param $file
     * @param null $quality
     * @return bool
     * @throws \Exception
     */
    public function save($file, $quality = null)
    {
        //獲取保存目的文件的擴展名
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $ext = strtolower($ext);
        if(!$ext || !in_array($ext, array('jpg', 'jpeg', 'gif', 'png')))
        {
            throw new \Exception('image save file must be jpg ,png,gif');
        }

        if($ext === 'gif')
        {
            imagegif($this->_im, $file);
            return true;
        }
        if($ext === 'jpeg' || $ext === 'jpg')
        {
            if($quality > 0)
            {
                if($quality < 1)
                {
                    $quality = 1;
                }
                if($quality > 100)
                {
                    $quality = 100;
                }

                imagejpeg($this->_im, $file, $quality);
            }
            else
            {
                imagejpeg($this->_im, $file);
            }
            return true;
        }

        if($ext === 'png')
        {
            imagepng($this->_im, $file);
            return true;
        }

    }
}

指定尺寸縮放 演示

require_once './lib/Image.php';

$image = new \Test\Lib\Image('../image/b.png');
$image->resize(400,200)->save('../image/b_400_200.png');

 

 

按比例縮放+旋轉 演示

require_once './lib/Image.php';

$image = new \Test\Lib\Image('../image/b.png');
$image->resizeByPercent(50)->rotate(1800)->show();
相關文章
相關標籤/搜索