@imagecopyresampled
元の縦横比を維持しながら、画像のサイズを変更してトリミングしようとしています。
アイデアは次のとおりです。1)サムネイルの寸法を修正します(fe 300x40)2)高さの中央からトリミングを開始します
ドキュメントと、stackoverflow に関する他の多くの質問を読み込もうとしましたが、結果はありませんでした。誰でも私を助けることができますか?? 私の実際のコードは次のとおりです。
//$img_height, $img_width [original size of the image]
$thumb_width = 300;
$thumb_height = 40;
$new_img = @imagecreatetruecolor($thumb_width, $thumb_height);
$middle = floor($img_height/2);
$src_x = 0;
$src_y = $middle-($thumb_width/2);
$src_w = $img_width;
$aspectRatio = $img_width/$thumb_width;
//$src_h = ?????
$imgCopyRes = @imagecopyresampled(
$new_img, $src_img,
0, 0,
$src_x, $src_y,
$thumb_width, $thumb_height,
$src_w, $src_h);
編集 :
@Joshua Burns に感謝します。クラスを読み、コードを編集して、ファイル全体を含めずに解決策を見つけました。
コード:
$target_width = 300;
$target_height = 40;
$new_img = @imagecreatetruecolor($target_width, $target_height);
$width_ratio = $target_width / $img_width;
$height_ratio = $target_height / $img_height;
if($width_ratio > $height_ratio) {
$resized_width = $target_width;
$resized_height = $img_height * $width_ratio;
} else {
$resized_height = $target_height;
$resized_width = $img_width * $height_ratio;
}
// Drop decimal values
$resized_width = round($resized_width);
$resized_height = round($resized_height);
// Calculations for centering the image
$offset_width = round(($target_width - $resized_width) / 2);
$offset_height = round(($target_height - $resized_height) / 2);
$imgCopyRes = @imagecopyresampled(
$new_img, $src_img,
$offset_width, $offset_height,
0, 0,
$resized_width, $resized_height,
$img_width, $img_height);