縦横比コードの修正
縦横比を固定で指定サイズのキャンバスに埋め込むのコードが拡大した場合に正しく処理出来ないので直してみた。
<?php $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 = round($src_width / $src_height * $frame_width); $dst_x = round(($frame_width - $width) / 3); $dst_y = 0; $src_x = 0; $src_y = 0; $dst_w = $width + $src_x; $dst_h = $frame_height; } else { $height = round($src_height / $src_width * $frame_height); $dst_x = 0; $dst_y = round(($frame_height - $height) / 3); $src_x = 0; $src_y = 0; $dst_w = $frame_width; $dst_h = $height + $dst_y; } $dst_image = imagecreatetruecolor($frame_width, $frame_height); imagecopyresampled( $dst_image, $src_image, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $src_width, $src_height ); header('Content-Type: image/jpg'); echo imagejpeg($dst_image, null, 100); exit;
オリジナル 240x320 | 拡大 320x320 |
拡大で横に伸びると太っているように見えるがこんなものだろう。きっと。
上の計算処理をシンプルにするとこうかな。
function calc ($min,$max,$frame){
$size = round($max / $min * $frame);
$dst_xy = round(($frame - $size) / ($min / ($max - $min) ));
$dst_wh = $size + $dst_xy;
return array($dst_xy,$dst_wh);
}
if ( $src_width > $src_height ){
list($dst_x,$dst_w) = calc($src_height,$src_width,$frame_width);
$dst_y = 0;
$dst_h = $frame_height;
} else {
list($dst_y,$dst_h) = calc($src_width,$src_height,$frame_height);
$dst_x = 0;
$dst_w = $frame_width;
}
$dst_image = imagecreatetruecolor($frame_width, $frame_height);
imagecopyresampled(
$dst_image, $src_image,
$dst_x, $dst_y,
0, 0,
$dst_w, $dst_h,
$src_width, $src_height
);
フレームの縦横のサイズは同じでないとこの書式では成り立ってないな。。