イメージの縦横の長い方を指定のサイズにし、はみ出した部分はサンプリングしない感じだ。また、容量に制限を設け10KB以内になるように処理した。
$width = 240; $height = 320; $filename = '0008.jpg'; $max_file_size = 10 * 1024; $bg_quality = 90; $size = getimagesize($filename); $img = imagecreatefromjpeg($filename); $resizedImg = imagecreatetruecolor($width, $height); if($size[1] < $size[0] * ($height / $width)){//horizontal $imageWidth = (int) (($height / $size[1]) * $size[0]); imagecopyresampled( $resizedImg, $img, 0, 0, ($size[0] - ($width / $height * $size[1])) / 2, 0, $imageWidth, $height, $size[0], $size[1] ); } else{//vertical $imageHeight = (int) (($width / $size[0]) * $size[1]); imagecopyresampled( $resizedImg, $img, 0, 0, 0, ($size[1] - ($height / $width * $size[0])) / 2, $width, $imageHeight, $size[0], $size[1] ); } $counter = 0; while(true){ imagejpeg($resizedImg, $filename, $bg_quality - (10 * $counter)); clearstatcache(); $counter++; if(filesize($filename) < $max_file_size || $counter > 9){ break; } }