画像を縦横比固定で指定サイズのキャンバスに埋め込む
縦横比を固定で指定サイズのキャンバスに埋め込む時、四隅は黒で画像を中央に持ってくるをやってみた。
$path = 'test.jpg'; $frame_width = 75; $frame_height = 75; $info = getimagesize($path); $src_width = $info[0]; $src_height = $info[1]; $src_image = imagecreatefromjpeg($path); if($src_width > $src_height){ $width = ($src_width > $frame_width) ? $frame_width : $src_width; $height = round($src_height * $frame_width / $src_width); }else{ $height = ($src_height > $frame_height) ? $frame_height : $src_height; $width = round($src_width * $frame_height / $src_height); } $x = round(($frame_width - $width) / 4); $y = round(($frame_height - $height) / 4); $dst_w = $frame_width - $x * 2; $dst_h = $frame_height - $y * 2; $dst_image = imagecreatetruecolor($frame_width, $frame_height); imagecopyresampled( $dst_image, $src_image, $x, $y, 0, 0, $dst_w, $dst_h, $src_width, $src_height ); header('Content-Type: image/jpg'); echo imagejpeg($dst_image, null, 100); exit;
追記 - 2011.05.21
サイズの小さい方をキャンバスに合わせるには上記コードの分岐を以下に変更すれば実現できる
if($src_width > $src_height){ ↓ if($src_width < $src_height){