萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 圖像處理類庫:驗證碼、縮略圖、文字生成圖片完整實現

類庫簡介

本類庫封裝常用 GD 圖像操作功能,包含驗證碼生成、縮略圖建立、純文字轉圖片等實用功能。採用鏈式調用設計,配置靈活,適合快速整合至專案中。

核心功能

  • Style():設定圖片樣式(尺寸、顏色、字體、對齊等),自動重置預設值
  • Create_Img_Png() / Create_Img_Jpeg():依樣式建立空白 PNG/JPEG 圖片
  • Create_Verify():生成干擾線、隨機字元的驗證碼圖片
  • Get_Verify():取得驗證碼值(MD5 加密)供 Session 驗證
  • Load_Img():載入現有圖片資源,支援 JPEG/PNG/GIF/WBMP
  • Create_Thumb():依載入圖片建立等比例縮略圖並儲存

完整類別代碼

<?php
if (!defined("__WEBROOT__")) define("__WEBROOT__", $_SERVER['DOCUMENT_ROOT']);

class Img {
    protected $_Img;        // 當前操作圖片資源
    protected $_FileImg;    // 載入的原始圖片資源
    protected $_FileInfo;   // 原始圖片資訊
    protected $_PicInfo;    // 原始圖片寬高資訊
    protected $_Rand = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ1234567890';
    protected $_Code = '';  // 驗證碼字串
    
    // 預設屬性
    public $Width = 300;
    public $Height = 80;
    public $BackgroundColor = "000000";
    public $Font = "/phps/Public/Font/ARIALNB.TTF";
    public $FontSize = 16;
    public $FontColor = "ffffff";
    public $Content = "Test Word";
    public $Align = "left";
    public $Codes = 4;
    public $Line = 6;
    public $LoadErr = '';
    
    // 重置為預設樣式
    protected function _Re_Set() {
        $this->Width = 100;
        $this->Height = 30;
        $this->BackgroundColor = "000000";
        $this->Font = "/phps/Public/Font/ARIALNB.TTF";
        $this->FontSize = 16;
        $this->FontColor = "ffffff";
        $this->Align = "left";
        $this->Codes = 4;
        $this->Line = 6;
    }
    
    // 設定樣式(鏈式調用)
    public function Style($Options) {
        $this->_Re_Set();
        foreach ($Options as $K => $V) {
            if (in_array($K, array('Width','Height','BackgroundColor','Font','FontSize','FontColor','Content','Align','Codes','Line','Snow'))) {
                if ($K == "BackgroundColor" || $K == "FontColor") {
                    if (preg_match("#([a-zA-Z0-9]{6})#", $V)) $this->$K = $V;
                } else {
                    $this->$K = $V;
                }
            }
        }
        return $this;
    }
    
    // 十六進位顏色轉 RGB 陣列
    protected function _Hex2Rgb($hex) {
        $hex = str_replace("#", "", $hex);
        if (strlen($hex) == 3) {
            $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
        }
        return array(
            hexdec($hex[0].$hex[1]),
            hexdec($hex[2].$hex[3]),
            hexdec($hex[4].$hex[5])
        );
    }
    
    // 建立 PNG 圖片
    public function Create_Img_Png() {
        $this->_Img = imagecreatetruecolor($this->Width, $this->Height);
        $bg = $this->_Hex2Rgb($this->BackgroundColor);
        $bgColor = imagecolorallocate($this->_Img, $bg[0], $bg[1], $bg[2]);
        imagefill($this->_Img, 0, 0, $bgColor);
        return $this;
    }
    
    // 建立 JPEG 圖片
    public function Create_Img_Jpeg() {
        $this->_Img = imagecreatetruecolor($this->Width, $this->Height);
        $bg = $this->_Hex2Rgb($this->BackgroundColor);
        $bgColor = imagecolorallocate($this->_Img, $bg[0], $bg[1], $bg[2]);
        imagefill($this->_Img, 0, 0, $bgColor);
        return $this;
    }
    
    // 生成驗證碼圖片
    public function Create_Verify() {
        $this->Create_Img_Png();
        $fontColor = $this->_Hex2Rgb($this->FontColor);
        $color = imagecolorallocate($this->_Img, $fontColor[0], $fontColor[1], $fontColor[2]);
        
        // 生成隨機驗證碼
        $this->_Code = '';
        for ($i = 0; $i < $this->Codes; $i++) {
            $this->_Code .= $this->_Rand[mt_rand(0, strlen($this->_Rand)-1)];
        }
        
        // 計算文字位置
        $x = ($this->Width - $this->FontSize * $this->Codes) / 2;
        $y = ($this->Height + $this->FontSize) / 2;
        
        // 繪製干擾線
        for ($i = 0; $i < $this->Line; $i++) {
            $lineColor = imagecolorallocate($this->_Img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
            imageline($this->_Img, mt_rand(0,$this->Width), mt_rand(0,$this->Height), mt_rand(0,$this->Width), mt_rand(0,$this->Height), $lineColor);
        }
        
        // 繪製驗證碼文字
        imagettftext($this->_Img, $this->FontSize, 0, $x, $y, $color, $this->Font, $this->_Code);
        return $this;
    }
    
    // 取得驗證碼(MD5)
    public function Get_Verify() {
        return md5($this->_Code);
    }
    
    // 載入圖片
    public function Load_Img($FilePath) {
        $fullPath = __WEBROOT__ . $FilePath;
        if (!file_exists($fullPath)) {
            $this->LoadErr = "File not found: $fullPath";
            return false;
        }
        $this->_FileInfo = getimagesize($fullPath);
        $this->_PicInfo = array('width' => $this->_FileInfo[0], 'height' => $this->_FileInfo[1]);
        switch ($this->_FileInfo[2]) {
            case IMAGETYPE_JPEG: $this->_FileImg = imagecreatefromjpeg($fullPath); break;
            case IMAGETYPE_PNG:  $this->_FileImg = imagecreatefrompng($fullPath); break;
            case IMAGETYPE_GIF:  $this->_FileImg = imagecreatefromgif($fullPath); break;
            case IMAGETYPE_WBMP: $this->_FileImg = imagecreatefromwbmp($fullPath); break;
            default: $this->LoadErr = "Unsupported image type"; return false;
        }
        return $this;
    }
    
    // 建立縮略圖
    public function Create_Thumb($FileName, $FilePath) {
        if (!$this->_FileImg) return false;
        $srcW = $this->_PicInfo['width'];
        $srcH = $this->_PicInfo['height'];
        $dstW = $this->Width;
        $dstH = $this->Height;
        
        // 等比例縮放計算
        $ratio = min($dstW/$srcW, $dstH/$srcH);
        $newW = (int)($srcW * $ratio);
        $newH = (int)($srcH * $ratio);
        $x = (int)(($dstW - $newW) / 2);
        $y = (int)(($dstH - $newH) / 2);
        
        $this->Create_Img_Png(); // 建立畫布
        imagecopyresampled($this->_Img, $this->_FileImg, $x, $y, 0, 0, $newW, $newH, $srcW, $srcH);
        
        $savePath = __WEBROOT__ . $FilePath . $FileName . '.png';
        imagepng($this->_Img, $savePath);
        return $savePath;
    }
    
    // 輸出圖片到瀏覽器
    public function Output($type = 'png') {
        header("Content-Type: image/$type");
        switch (strtolower($type)) {
            case 'jpeg': case 'jpg': imagejpeg($this->_Img); break;
            case 'png': imagepng($this->_Img); break;
            case 'gif': imagegif($this->_Img); break;
        }
        imagedestroy($this->_Img);
    }
}

使用範例

1. 生成驗證碼

<?php
require 'Img.php';
$img = new Img();
$img->Style(array(
    'Width' => 120,
    'Height' => 40,
    'FontSize' => 20,
    'Codes' => 4,
    'Line' => 8,
    'FontColor' => '000000',
    'BackgroundColor' => 'ffffff'
))->Create_Verify()->Output('png');

// 儲存驗證碼到 Session
$_SESSION['verify_code'] = $img->Get_Verify();

2. 建立縮略圖

<?php
$img = new Img();
$img->Style(array('Width' => 200, 'Height' => 200));
$img->Load_Img('/uploads/photo.jpg')->Create_Thumb('thumb_', '/uploads/thumbs/');

3. 文字生成圖片

<?php
$img = new Img();
$img->Style(array(
    'Width' => 400,
    'Height' => 100,
    'Content' => 'Hello World',
    'FontSize' => 24,
    'FontColor' => '333333',
    'BackgroundColor' => 'f0f0f0',
    'Align' => 'center'
))->Create_Img_Png()->Output('png');

擴充建議

  • 加入水印功能(文字/圖片水印)
  • 支援更多字體格式(OTF、WOFF)
  • 整合 Imagick 擴充以獲得更好效能與格式支援
  • 新增圖片濾鏡(銳化、模糊、灰階等)
  • 實作圖片裁切、旋轉、翻轉功能

此類庫提供輕量級、無依賴的圖像處理解決方案,適合中小型專案快速導入。生產環境建議加入錯誤日誌、快取機制與單元測試。

copyright © 萬盛學電腦網 all rights reserved