萬盛學電腦網

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

PHP 服务端图片动态缩放:GD 库实现等比缩放与实时输出

应用场景

  • 缩略图实时生成,避免预生成多规格占用存储
  • 用户头像、商品列表图自适应裁剪
  • 防盗链、水印叠加等后处理统一入口

核心函数:imageResizer

<?php
function imageResizer($url, $width, $height) {
    // 仅支持 JPEG,生产环境需根据 mime 动态调用 imagecreatefrompng/gif/webp
    header('Content-Type: image/jpeg');

    list($w_orig, $h_orig) = getimagesize($url);
    $ratio = $w_orig / $h_orig;

    // 等比缩放:以短边为准
    if ($width / $height > $ratio) {
        $width = $height * $ratio;
    } else {
        $height = $width / $ratio;
    }

    $dst = imagecreatetruecolor($width, $height);
    $src = imagecreatefromjpeg($url);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $w_orig, $h_orig);

    imagejpeg($dst, null, 90); // 直接输出,质量 90
    imagedestroy($dst);
    imagedestroy($src);
}

// 入口分发
$method = $_SERVER['REQUEST_METHOD'];
$src = $method === 'POST' ? $_POST['url'] : $_GET['url'];
$w = $method === 'POST' ? $_POST['w'] : $_GET['w'];
$h = $method === 'POST' ? $_POST['h'] : $_GET['h'];

if ($src && $w && $h) {
    imageResizer($src, (int)$w, (int)$h);
}

// 简化调用辅助函数
function loadImage($url, $width, $height) {
    return 'image.php?url=' . urlencode($url) . "&w=$width&h=$height";
}

前端调用

<img src="<?php echo loadImage('photo.jpg', 300, 200); ?>" alt="缩略图" />

安全与性能加固

  1. 白名单域名/路径:防止 SSRF 任意文件读取或内网探测。
  2. 缓存生成结果:以 md5($url.$w.$h) 命名缓存文件,后续请求直接 readfile 或 X-Sendfile。
  3. 限制最大尺寸:如 max($w,$h) <= 2000,防止恶意大图耗尽内存。
  4. 支持多格式:用 getimagesize 返回的 mime 分发 imagecreatefrom* 与 imagejpeg/png/webp。
  5. CDN 配合:给缩略图 URL 加版本号或哈希,配置长期缓存头。

现代替代:Intervention Image

// composer require intervention/image
use Intervention\Image\ImageManagerStatic as Image;
$img = Image::make('photo.jpg')->fit(300, 200)->encode('jpg', 80);
return Response::make($img, 200, ['Content-Type' => 'image/jpeg']);
copyright © 萬盛學電腦網 all rights reserved