如何在 PHP 中調整圖片大小?


可以使用 ImageMagick 或 GD 函式來調整影像大小。如果使用 GD 的函式,那麼對原始數碼相機影像進行取樣時也會減小影像檔案大小。我們將在下面的程式碼中看到如何使用 GD 來調整影像大小。

function image_resize($file_name, $width, $height, $crop=FALSE) {
   list($wid, $ht) = getimagesize($file_name);
   $r = $wid / $ht;
   if ($crop) {
      if ($wid > $ht) {
         $wid = ceil($wid-($width*abs($r-$width/$height)));
      } else {
         $ht = ceil($ht-($ht*abs($r-$w/$h)));
      }
      $new_width = $width;
      $new_height = $height;
   } else {
      if ($width/$height > $r) {
         $new_width = $height*$r;
         $new_height = $height;
      } else {
         $new_height = $width/$r;
         $new_width = $width;
      }
   }
   $source = imagecreatefromjpeg($file_name);
   $dst = imagecreatetruecolor($new_width, $new_height);
   image_copy_resampled($dst, $source, 0, 0, 0, 0, $new_width, $new_height, $wid, $ht);
   return $dst;
}
$img_to_resize = image_resize(‘path-to-jpg-image’, 250, 250);

更新時間:2020 年 04 月 06 日

5K+ 瀏覽

開始你的 職業

透過完成課程獲得認證

開始
廣告