在 Web 開發中,處理使用者上傳的圖片是常見需求。本文提供兩款 PHP GD 庫代碼範例,分別實現「等比例縮放」與「固定尺寸縮略圖(不足處填白)」功能,適合快速整合至專案中。
此範例將原始圖片縮放至指定寬高(257×522),若原圖尺寸小於目標尺寸,則以白色背景填補空白區域,確保輸出圖片尺寸一致。
<?php
header("content-type:image/jpeg");
$filename = 'hsdir/mljntc2p.jpg';
$im = imagecreatefromjpeg($filename);
$h = imagesy($im); // 取得原圖高度
$new_img_width = 257;
$new_img_height = 522;
$newim = imagecreate($new_img_width, $new_img_height);
$white = imagecolorallocate($newim, 255, 255, 255); // 設定背景白色
// 將原圖複製至新畫布(左上角對齊)
imagecopyresized($newim, $im, 0, 0, 0, 0, $new_img_width, $new_img_height, $new_img_width, $new_img_height);
// 從原圖高度處向下填充白色矩形,覆蓋多餘區域
imagefilledrectangle($newim, 0, $h, $new_img_width, $new_img_height, $white);
imagejpeg($newim);
imagedestroy($newim);
imagedestroy($im);
?>
此範例直接將圖片縮放至 80×150 像素,不進行填充,適合需要統一縮略圖尺寸的場景。
<?php
header("content-type:image/jpeg");
$filename = 'myface.jpg';
$im = imagecreatefromjpeg($filename);
$new_img_width = 80;
$new_img_height = 150;
$newim = imagecreate($new_img_width, $new_img_height);
$white = imagecolorallocate($newim, 255, 255, 255);
imagecopyresized($newim, $im, 0, 0, 0, 0, $new_img_width, $new_img_height, $new_img_width, $new_img_height);
imagejpeg($newim);
imagedestroy($newim);
imagedestroy($im);
?>
imagecreatetruecolor 搭配 imagecolortransparent 或 imagesavealpha。