萬盛學電腦網

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

PHP 判斷 GIF 是否為動圖:檢測 Netscape 2.0 擴展塊

GIF 動畫(GIF89a)在檔案中包含 **Netscape 2.0 應用擴展塊**,標識循環次數。靜態 GIF(含透明 GIF89a)無此塊。通過讀取檔案二進制內容搜尋特徵字串即可精準判斷。

核心特徵字串

0x21 0xFF 0x0B 'NETSCAPE2.0'
/* 0x21 = Extension Introducer
   0xFF = Application Extension Label
   0x0B = Block Size (11 bytes)
   "NETSCAPE2.0" = Application Identifier + Authentication Code */

高效檢測函式(僅讀前 1KB 即可)

<?php
/**
 * 判斷 GIF 是否為動畫
 * @param string $filePath
 * @return bool
 */
function isAnimatedGif(string $filePath): bool
{
    $fp = @fopen($filePath, 'rb');
    if (!$fp) return false;

    // 僅讀取前 1024 字節,擴展塊通常在文件開頭附近
    $header = fread($fp, 1024);
    fclose($fp);

    if ($header === false || strlen($header) < 13) return false;

    // 搜尋特徵序列
    $needle = "\x21\xFF\x0B" . 'NETSCAPE2.0';
    return strpos($header, $needle) !== false;
}

// 用法
var_dump(isAnimatedGif('static.gif'));   // false
var_dump(isAnimatedGif('animation.gif'));// true
?>

替代方案:`getimagesize()` 多幀檢測(PHP 5.3+)

<?php
function isAnimatedGifV2(string $filePath): bool
{
    $info = @getimagesize($filePath);
    if (!$info || $info[2] !== IMAGETYPE_GIF) return false;
    // PHP 7.1+ 返回陣列包含 'frames'、'loops'(需啟用 exif)
    // 通用做法:嘗試讀取多幀
    $frames = 0;
    $fp = fopen($filePath, 'rb');
    while (!feof($fp) && $frames < 2) {
        $byte = fread($fp, 1);
        if ($byte === "\x21") { // Extension
            $label = fread($fp, 1);
            if ($label === "\xF9") { // Graphic Control Extension
                fseek($fp, 4, SEEK_CUR); // 跳過 block size + packed + delay
                $frames++;
            } elseif ($label === "\xFF") { // Application Extension
                $size = ord(fread($fp, 1));
                fseek($fp, $size, SEEK_CUR);
            } elseif ($label === "\x01") { // Plain Text Extension
                fseek($fp, 12, SEEK_CUR);
            } else {
                // Comment Extension 0xFE
                do { $b = fread($fp, 1); } while ($b !== "\x00");
            }
        } elseif ($byte === "\x2C") { // Image Descriptor
            $frames++;
            if ($frames > 1) break;
            fseek($fp, 9, SEEK_CUR); // 跳過描述符
            $lct = fread($fp, 1);
            if (ord($lct) & 0x80) fseek($fp, 3 * (1 << (ord($lct) & 0x07)), SEEK_CUR);
            // 跳過 LZW 最小碼長 + 資料塊
            do { $blk = ord(fread($fp, 1)); fseek($fp, $blk, SEEK_CUR); } while ($blk);
        } else {
            break;
        }
    }
    fclose($fp);
    return $frames > 1;
}
?>

效能與選擇

方法讀取量速度準確度依賴
特徵字串搜尋~1KB極快高(標準 GIF89a)無
解析幀結構全檔(最壞)較慢最高(非標準也能檢測)無
Imagick/GD全檔解碼慢高擴展

推薦**特徵字串搜尋**作為首選(快、準、無依賴),異常情況下回退到幀解析。

copyright © 萬盛學電腦網 all rights reserved