萬盛學電腦網

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

PHP 圖片裁剪函數:等比縮放並填滿目標尺寸(不變形、不留白)

上傳圖片後常需自動裁剪為固定尺寸(如縮圖),要求圖片不變形、不留白邊。本函數 my_image_resize() 實現「以長邊為準縮放,再居中裁剪」邏輯,支援 JPEG/PNG/GIF。

函數完整程式碼

<?php
/**
 * 任意尺寸裁剪,保持比例、不變形、不留白
 * @param string $src_file 來源圖片路徑
 * @param string $dst_file 輸出圖片路徑
 * @param int $new_width 目標寬度
 * @param int $new_height 目標高度
 */
function my_image_resize($src_file, $dst_file, $new_width, $new_height) {
    $new_width = intval($new_width);
    $new_height = intval($new_height);
    if ($new_width < 1 || $new_height < 1) exit('params width or height error!');
    if (!file_exists($src_file)) exit($src_file . ' is not exists!');

    $type = exif_imagetype($src_file);
    $support = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF];
    if (!in_array($type, $support, true)) exit('only support jpg, gif or png');

    // 載入圖片資源
    switch ($type) {
        case IMAGETYPE_JPEG: $src_img = imagecreatefromjpeg($src_file); break;
        case IMAGETYPE_PNG:  $src_img = imagecreatefrompng($src_file); break;
        case IMAGETYPE_GIF:  $src_img = imagecreatefromgif($src_file); break;
        default: exit('Load image error!');
    }

    $w = imagesx($src_img);
    $h = imagesy($src_img);
    $ratio_w = $new_width / $w;
    $ratio_h = $new_height / $h;

    // 情況一:目標長寬皆小於或皆大於原圖 → 取較大比例縮放/放大,再裁剪
    if (($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)) {
        $ratio = ($ratio_w < $ratio_h) ? $ratio_h : $ratio_w;
        $inter_w = (int)($new_width / $ratio);
        $inter_h = (int)($new_height / $ratio);
        $inter_img = imagecreatetruecolor($inter_w, $inter_h);
        imagecopy($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h);

        $new_img = imagecreatetruecolor($new_width, $new_height);
        imagecopyresampled($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height, $inter_w, $inter_h);
    }
    // 情況二:一邊放大、一邊縮小 → 先放大到滿足較大比例,再裁剪
    else {
        $ratio = ($ratio_h > $ratio_w) ? $ratio_h : $ratio_w;
        $inter_w = (int)($w * $ratio);
        $inter_h = (int)($h * $ratio);
        $inter_img = imagecreatetruecolor($inter_w, $inter_h);
        imagecopyresampled($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h, $w, $h);

        $new_img = imagecreatetruecolor($new_width, $new_height);
        imagecopy($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height);
    }

    // 輸出
    switch ($type) {
        case IMAGETYPE_JPEG: imagejpeg($new_img, $dst_file, 100); break;
        case IMAGETYPE_PNG:  imagepng($new_img, $dst_file, 100); break;
        case IMAGETYPE_GIF:  imagegif($new_img, $dst_file, 100); break;
    }
    imagedestroy($src_img);
    imagedestroy($inter_img);
    imagedestroy($new_img);
}

// 使用範例
my_image_resize('test.gif', 'thumb.gif', 100, 100);
?>

核心邏輯說明

  1. 計算目標寬高與原圖寬高的比例 ratio_w、ratio_h。
  2. 若同方向縮放(同大或同小),取較大比例 → 產生中間圖 → 再縮放到目標尺寸(等同裁剪)。
  3. 若異方向縮放(一大一小),取較大比例放大原圖 → 直接裁剪目標區域。
  4. 全程使用 imagecopyresampled 保證畫質。
copyright © 萬盛學電腦網 all rights reserved