LoginSignup
24
25

More than 5 years have passed since last update.

【メモ】PHPで画像の比率はそのままに縮小する

Last updated at Posted at 2014-09-04

画像の比率を維持したまま、縮小してほしいという要望があったため、
メモとして残します。

// 画像サイズ取得

list($width, $height, $type, $attr) = getimagesize(画像パス);

$newwidth = 0; // 新しい横幅
$newheight = 0; // 新しい縦幅
$w = 200; // 最大横幅
$h = 50; // 最大縦幅

// 両方オーバーしていた場合 
if ($h < $height && $w < $width)  { 
 if ($w < $h) { 
  $newwidth = $w; 
  $newheight = $height * ($w / $width); 
 } else if ($h < $w) { 
  $newwidth = $width * ($h / $height); 
  $newheight = $h; 
 } else { 
   if ($width < $height) { 
   $newwidth = $width * ($h / $height); 
   $newheight = $h; 
  } else if($height < $width) { 
   $newwidth = $w; 
   $newheight = $height * ($w / $width); 
  }
 }
} else if ($height < $h && $width < $w) { // 両方オーバーしていない場合 
 $newwidth = $width; 
 $newheight = $height; 
} else if ($h < $height && $width <= $w) { 
 // 縦がオーバー、横は新しい横より短い場合 
 // 縦がオーバー、横は同じ長さの場合
 $newwidth = $width * ($h / $height); 
 $newheight = $h; 
} else if ($height <= $h && $w < $width) { 
 // 縦が新しい縦より短く、横はオーバーしている場合 
 // 縦は同じ長さ、横はオーバーしている場合 
 $newwidth = $w; 
 $newheight = $height * ($w / $width); 
} else if ($height == $h && $width < $w) { 
 // 横が新しい横より短く、縦は同じ長さの場合 
 $newwidth = $width * ($h / $height); 
 $newheight = $h; 
} else if ($height < $h && $width == $w) { 
 // 縦が新しい縦より短く、横は同じ長さの場合 
 $newwidth = $w; 
 $newheight = $height * ($w / $width); 
} else { 
 // 縦も横も、新しい長さと同じ長さの場合 
 // または、縦と横が同じ長さで、かつ最大サイズを超えない場合 
 $newwidth = $width; 
 $newheight = $height; 
}

参考サイト

24
25
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
25