首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 簡易等比縮放:getimagesize + imagecopyresampled 核心代碼解析

     編輯:PHP 相關知識

核心邏輯三步驟

  1. getimagesize() 取得原圖寬高
  2. 計算目標尺寸(乘以比例或依最大寬高限制)
  3. imagecreatetruecolor() + imagecopyresampled() 高品質縮放

最精簡可用代碼

<?php
$file = 'photo.jpg';
$scale = 0.5; // 縮小 50%

header('Content-Type: image/jpeg');
list($w, $h) = getimagesize($file);
$nw = (int)($w * $scale);
$nh = (int)($h * $scale);

$dst = imagecreatetruecolor($nw, $nh);
$src = imagecreatefromjpeg($file);
imagecopyresampled($dst, $src, 0,0,0,0, $nw,$nh, $w,$h);

imagejpeg($dst, null, 100); // 直接輸出,品質 100
imagedestroy($dst); imagedestroy($src);
?>

進階:限制最大寬高(等比縮放不超過框)

<?php
function resizeFit($srcFile, $maxW, $maxH, $outFile = null, $quality = 90) {
    $info = getimagesize($srcFile);
    $ratio = min($maxW/$info[0], $maxH/$info[1], 1); // 不放大
    $nw = (int)($info[0] * $ratio);
    $nh = (int)($info[1] * $ratio);

    $src = loadAny($srcFile); // 依類型載入
    $dst = imagecreatetruecolor($nw, $nh);
    // 透明支援
    if (in_array($info[2], [IMAGETYPE_PNG, IMAGETYPE_GIF])) {
        imagealphablending($dst, false);
        imagesavealpha($dst, true);
        $tr = imagecolorallocatealpha($dst, 0,0,0, 127);
        imagefill($dst, 0,0, $tr);
    }
    imagecopyresampled($dst, $src, 0,0,0,0, $nw,$nh, $info[0],$info[1]);

    if ($outFile) saveAny($dst, $outFile, $info[2], $quality);
    else { header('Content-Type: '.$info['mime']); outputAny($dst, $info[2], $quality); }
    imagedestroy($src); imagedestroy($dst);
}

function loadAny($f) {
    $t = (getimagesize($f))[2];
    return match($t) {
        IMAGETYPE_JPEG => imagecreatefromjpeg($f),
        IMAGETYPE_PNG  => imagecreatefrompng($f),
        IMAGETYPE_GIF  => imagecreatefromgif($f),
        default => null
    };
}
function saveAny($im, $f, $type, $q) {
    match($type) {
        IMAGETYPE_JPEG => imagejpeg($im, $f, $q),
        IMAGETYPE_PNG  => imagepng($im, $f),
        IMAGETYPE_GIF  => imagegif($im, $f),
    };
}
function outputAny($im, $type, $q) {
    match($type) {
        IMAGETYPE_JPEG => imagejpeg($im, null, $q),
        IMAGETYPE_PNG  => imagepng($im),
        IMAGETYPE_GIF  => imagegif($im),
    };
}

// 用法
resizeFit('upload.jpg', 800, 600, 'thumb_800x600.jpg');
?>

imagecopyresampled vs imagecopyresized

特性imagecopyresampledimagecopyresized
插值算法雙三次/雙線性(平滑)最近鄰(鋸齒)
速度較慢較快
品質高(推薦正式縮圖)低(適合即時預覽)
參數相同相同

輸出品質參數

  • JPEG:imagejpeg($im, $file, 85)(0-100,建議 85-95)
  • PNG:imagepng($im, $file, 6)(0-9,6 平衡速度/大小)
  • WebP:imagewebp($im, $file, 85)(需 GD 支援 WebP)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved