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

PHP 圖片等比例縮放與固定尺寸縮略圖生成代碼範例

     編輯:PHP 相關知識

PHP 圖片處理:等比例縮放與固定尺寸縮略圖

在 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);
?>

使用建議

  • 確保伺服器已啟用 GD 擴展(支援 JPEG、PNG、GIF)。
  • 實際部署時,建議加入錯誤處理(如檔案是否存在、圖片格式驗證)。
  • 若需支援透明背景(PNG/GIF),請改用 imagecreatetruecolor 搭配 imagecolortransparent 或 imagesavealpha。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved