萬盛學電腦網

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

PHP GD 庫批次下載網頁所有圖片實作類別

需求分析

抓取網頁所有 <img> 標籤的 src 屬性,處理相對/絕對路徑、去重,再逐一下載儲存。封裝為 DownImage 類別提升複用性。

主程式流程

<?php
header("Content-type:text/html; charset=utf-8");
if (!empty($_POST['submit'])) {
    $url = $_POST['url'];
    $url_fields = parse_url($url);
    $main_url = $url_fields['host'];
    $base_url = substr($url, 0, strrpos($url, '/') + 1);

    // 使用 stream_context 設定代理(可選)
    $opts = ['http' => ['request_fulluri' => true]];
    $context = stream_context_create($opts);
    $content = file_get_contents($url, false, $context);

    // 正則擷取所有 img src
    $reg = '/<img.*?src=["\'](.*?)["\'].*?>/i';
    preg_match_all($reg, $content, $matches);
    $count = count($matches[0]);

    // 處理相對路徑轉絕對路徑
    for ($i = 0; $i < $count; $i++) {
        $src = $matches[1][$i];
        if (!strpos('a' . $src, 'http')) {
            if (strpos('a' . $src, '/') !== false) {
                $matches[1][$i] = 'https://' . $main_url . $src;
            } else {
                $matches[1][$i] = $base_url . $src;
            }
        }
    }

    // 去重
    $img_arr = array_unique($matches[1]);

    // 批次下載
    $getImg = new DownImage();
    $getImg->save_address = './pic/';
    foreach ($img_arr as $src) {
        $getImg->source = $src;
        $getImg->download();
    }
    echo "下載完成!";
}
?>

DownImage 類別核心

class DownImage {
    public $source;        // 遠端圖片 URL
    public $save_address;  // 本地儲存目錄
    public $set_extension; // 強制副檔名
    public $quality;       // JPEG 品質 0-100

    public function download() {
        $info = @getimagesize($this->source);
        if (!$info) return false;
        $mime = $info['mime'];
        $type = substr(strrchr($mime, '/'), 1);

        // 同單圖下載的 switch 選擇函式...
        // (略,同上一篇文章)

        // 組合本地檔名
        if (isset($this->set_extension)) {
            $ext = strrchr($this->source, ".");
            $newname = basename(substr($this->source, 0, -strlen($ext))) . '.' . $new_img_ext;
        } else {
            $newname = basename($this->source);
        }
        $save_path = $this->save_address . $newname;

        $img = @$img_create_func($this->source);
        if (!$img) return false;

        if (isset($image_quality)) {
            $save_img = @$img_save_func($img, $save_path, $image_quality);
        } else {
            $save_img = @$img_save_func($img, $save_path);
        }
        return $save_img;
    }
}

表單介面

<form method="POST" action="">
遠端 URL:<input type="text" name="url" size=30 />
<input type="submit" name="submit" value="下載該頁面所有圖片" />
</form>

運行結果

批次下載結果示意圖

改進建議

  • 加入非同步/多執行緒下載(如 cURL multi 或 Swoole)提升速度。
  • 支援 srcset、data-src 等延遲載入屬性。
  • 加入圖片尺寸/格式過濾、重新壓縮、水印等後處理。
copyright © 萬盛學電腦網 all rights reserved