PHP 画像の縮小(リサイズ)
public function resize_image($tmp_file){ $w = 96; $h = 96;
list($width, $height, $type) = getimagesize($tmp_file);
if($width > $w || $height > $h){ //はみ出している if($width >= $height){ $new_width = $w; $x = 0; $new_height = round($h * $height / $width); $y = round(($h - $new_height) / 2); }else{ $new_height = $h; $y = 0; $new_width = round($w * $width / $height); $x = round(($w - $new_width) / 2); } }else{ //はみ出してない $new_width = $width; $new_height = $height; $x = round(($w - $width) / 2); $y = round(($h - $height) / 2); }
//背景画像 $canvas = imagecreatetruecolor($w, $h); $bcolor = imagecolorallocate($canvas, 255, 255, 255); imagefilledrectangle($canvas,0,0,$w,$h,$bcolor);
//画像インスタンス生成 switch($type){ case 1: //gif $image = imagecreatefromgif($tmp_file); break; case 2: //jpeg $image = imagecreatefromjpeg($tmp_file); break; case 3: //png $image = imagecreatefrompng($tmp_file); }
// 背景画像に、画像をコピーする imagecopyresampled( $canvas, // 背景画像 $image, // コピー元画像 $x, // 背景画像のはりつけ位置(x座標) $y, // 背景画像のはりつけ位置(y座標) 0, // コピー元画像のコピー開始位置(x座標) 0, // コピー元画像のコピー開始位置(y座標) $new_width, // 背景画像のはりつける幅 $new_height, // 背景画像のはりつける高さ $width, // コピー元画像のコピーする幅 $height // コピー元画像のコピーする高さ );
//画像の出力 switch($type){ case 1: //gif imagejgif($canvas, $tmp_file); break; case 2: //jpeg imagejpeg($canvas, $tmp_file,100); break; case 3: //png imagepng($canvas, $tmp_file,9); } imagedestroy($canvas);
return true;}